Angular指令不能用于范围ng-model

时间:2015-11-27 11:39:16

标签: javascript angularjs angularjs-directive angularjs-scope

我尝试使用控制器$ scope来填充具有现有值的表单,以将这些值传递给DOM。 现在,我使用指令在特定的选择菜单(我使用bootstrap form helpers)菜单中读取和写入值:

app.directive('currencypicker', function () {
    return {
        restrict: 'A',
        require: '?ngModel',
        scope: {
            ngModel: '='
        },
     link: function (scope, elem, attrs, ctrl) {
         elem.addClass('bfh-currencies');
         elem.addClass('bfh-selectbox');

         elem.bfhselectbox({
             filter: (elem.attr('data-filter') == 'true') ? true : false
         }).on('change.bfhselectbox', function() {
            return scope.$apply(function () {
                return scope.ngModel = elem.val();
            });
         });

         return elem.bfhcurrencies({
             flags: (elem.attr('data-flags') == 'true') ? true : false,
             currency: scope.ngModel || 'EUR'
         });
       }
    };
});

这里是HTML代码段

<div currencypicker id="cost-currency" data-flags="true" data-filter="true" ng-model="newEvent.cost_currency"></div>

问题在于,当我尝试使用scope.ngModel将我的模型值分配给 currency 属性时,它总是评估为未定义,因此&#39; EUR&#39;分配了值,我用firebug检查了我的范围,其中ngModel值是&#34; GBP&#34;。 我无法弄清楚它为什么会发生。

1 个答案:

答案 0 :(得分:0)

您必须使用指令的方式如下:

app.directive('currencypicker', function () {
    return {
        restrict: 'A',
        require: '?ngModel',
        //template : you have no template nor url template?
        link: function (scope, elem, attrs, ngModelCtrl) {

            // You can have your "ngModelValue" into ngModelCtrl.$viewValue

            // Also, you now have access to all the functions declared into ngModelController
        }
    };
});

如果您想了解有关该主题的更多信息,请随时查看该文档:https://docs.angularjs.org/api/ng/type/ngModel.NgModelController