Angular指令无法确定ng模型的范围

Angular directive can not scope ng-model

本文关键字:范围 模型 ng 指令 无法确定 Angular      更新时间:2023-09-26

我正试图使用控制器$scope将现有值传递给DOM,用现有值填充表单。现在,我正在使用一个指令来读取和写入特定选择菜单(在这里我使用引导表单助手)中的值:

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