[英]Select custom directive and ng-change
使用帶有自定義指令的<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
注冊監聽器的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
可能不適合您的情況。
或者你可以ngModel
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.