Abel D
Abel D

Reputation: 1080

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');
            }
        }
    }
});

Upvotes: 5

Views: 4703

Answers (2)

scniro
scniro

Reputation: 16989

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

Upvotes: 2

New Dev
New Dev

Reputation: 49590

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');
   }
}

Upvotes: 4

Related Questions