Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select custom directive and ng-change

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');
            }
        }
    }
});
like image 214
Abel D Avatar asked Jul 07 '15 18:07

Abel D


2 Answers

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');
   }
}
like image 113
New Dev Avatar answered Oct 12 '22 09:10

New Dev


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

like image 29
scniro Avatar answered Oct 12 '22 08:10

scniro