繁体   English   中英

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

[英]Angular directive can not scope ng-model

我正在尝试使用控制器$ 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属性时,它总是评估为undefined,因此分配了'EUR'值,我用firebug检查了我的范围,其中ngModel值是“GBP”。 我无法弄清楚它为什么会发生。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM