admin管理员组文章数量:1332395
Using <select>
with a custom directive, I want to run a function when the value is changed.
html
<select name="user_type" ng-model="user_type" user-type ng-change="check_type()">
directive
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');
}
}
}
});
Using <select>
with a custom directive, I want to run a function when the value is changed.
html
<select name="user_type" ng-model="user_type" user-type ng-change="check_type()">
directive
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');
}
}
}
});
Share
Improve this question
edited Jul 7, 2015 at 18:58
scniro
17k8 gold badges66 silver badges107 bronze badges
asked Jul 7, 2015 at 18:28
Abel DAbel D
1,0801 gold badge19 silver badges30 bronze badges
2 Answers
Reset to default 4Since you have an isolate scope, your check_type
is not in the same scope as the ng-change
expression. And you wouldn't want it to be so.
Instead, ng-model
provides a way to register a listener with ngModel.$viewChangeListeners
- which is exactly what ngChange
directive uses - to hook into view model change events.
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');
}
}
Because of your isolate scope, you can include a call to $parent
to achieve your result. Try this change...
link: function(scope, elem, attrs) {
scope.$parent.check_type = function() {
console.log('changed');
}
}
However, calling $parent
may not be ideal for your situation.
Alternatively you can ditch ng-change
and instead $watch
your ngModel
. This could be acplished as such...
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
本文标签: javascriptSelect custom directive and ngchangeStack Overflow
版权声明:本文标题:javascript - Select custom directive and ng-change - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742281833a2446236.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论