我正在尝试使用 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/