Abe*_*l D 5 html javascript angularjs angularjs-directive
使用<select>自定义指令,我想在更改值时运行函数.
HTML
<select name="user_type" ng-model="user_type" user-type ng-change="check_type()">
Run Code Online (Sandbox Code Playgroud)
指示
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');
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
由于您有一个隔离范围,因此您的范围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');
}
}
Run Code Online (Sandbox Code Playgroud)