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');
}
}
}
});
Since 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 accomplished 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With