使用 <select>
使用自定义指令,我想在值更改时运行一个函数。
html
<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
指令所使用的 -挂接到 View 模型更改事件。
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');
}
}
关于javascript - 选择自定义指令和 ng-change,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31276542/