function prMySelects() {
var ddo = {
restrict: 'E',
templateUrl: 'template.html',
require: '?ngModel',
scope: {
ngModel: '='
},
controller: prMySelectsController,
controllerAs: 'vm',
bindToController: true
};
return ddo;
}
function prMySelectsController($locale) {
...
}
我需要在指令 Controller 内部做一些检查并设置 ngModel.$setValidity('some', false),但出现 ngModel is not defined
错误。注入(inject) ngModel 没有帮助...
PS 我知道我可以在 link
中访问它,但是是否可以在指令 controller
中访问 ngModel Controller ?
最佳答案
这种功能最好在指令的链接函数中完成。
function prMySelects() {
return {
restrict: 'E',
require: '?ngModel',
link: function(scope, element, attributes, ngModel) {
scope.theModel = ngModel;
},
controller: function() {
var vm = this;
vm.theModel.$setViewValue...
}
}
}
在这种情况下,您实际上是在连接到 ngModel Controller ,并且不需要您在作用域中实际指定它。
关于directive - 如何从指令 Controller 访问 ngModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37146933/