使用带有自定义指令的<select>
,我想在值改变时运行一个函数。
<select name="user_type" ng-model="user_type" user-type ng-change="check_type()">
指令gb_dash.directive('userType', function(){
return{
restrict: 'A',
require: '^ngModel',
scope:{
check_type: '&'
},
link: function(scope, elem, attrs){
scope.check_type = function(){
console.log('changed');
}
}
}
});
由于您有一个隔离作用域,因此您的check_type
与ng-change
表达式不在同一作用域中。你也不希望这样。
相反,ng-model
提供了一种向ngModel.$viewChangeListeners
注册侦听器的方法-这正是ngChange
指令使用的-挂钩到视图模型更改事件。
require: "ngModel",
scope: { }, // to mimic your directive - doesn't have to be isolate scope
link: function(scope, element, attrs, ngModel){
ngModel.$viewChangeListeners.push(function(){
console.log('changed');
}
}
由于您的隔离作用域,您可以包含对$parent
的调用来实现您的结果。
link: function(scope, elem, attrs) {
scope.$parent.check_type = function() {
console.log('changed');
}
}
但是,调用$parent
可能不适合您的情况。
或者你可以放弃ng-change
,而把$watch
换成ngModel
。这可以这样完成…
link: function(scope, elem, attrs, ngModel) {
scope.$watch(function() {
return ngModel.$modelValue;
}, function(newValue, oldValue) {
console.log('model value changed...', newValue, oldValue);
}, true);
}
JSFiddle Link - $parent
demo
JSFiddle Link - $watch
demo