javascript - Angular 指令不能作用于 ng-model

标签 javascript angularjs angularjs-directive angularjs-scope

我正在尝试使用 Controller $scope 将现有值传递给 DOM 来填充表单。 现在,我正在使用指令在特定的选择菜单(我使用 Bootstrap 表单助手)菜单中读取和写入值:

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 属性时,它的计算结果总是未定义,因此分配了“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

关于javascript - Angular 指令不能作用于 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33956567/

相关文章:

javascript - Angularjs:在自定义指令中,我需要读取使用 ngClick 方法传递的参数

javascript - 在 Angular Controller 之间共享大对象

javascript - 创建在应用程序加载时调用方法的 AngularJS 对象

javascript - 如何向指令添加 bool 属性?

javascript - KnockoutJS 复选框列表不绑定(bind)所选值

javascript - 将字符串数组解析为 MVC 方法

javascript - 无法获取要插入 JavaScript 字符串的参数值

javascript - 指令中的 Angular 范围怪异

javascript - 什么是 $cacheFactory?

html - Angular 使固定显示元素与 "sibling"大小相同