Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement ng-change for custom directive for select list?

My directive usage code

       <input-select ng-model="someModel" ng-change="someFunction()"
   options="countries"></input-select>

My directive code

 .directive('inputSelect', function () {
    return {
        templateUrl: 'someTemplate.html',
        restrict: 'E',
        scope: {
            ngModel: '=',
            ngChange: '='
        }
    };
});

My directive template

    <select 
            ng-model="ngModel" ng-init="ngModel "
            ng-options="option[optionId] as option[optionName] for option in options"
            ng-change="ngChange">
    </select>

So, when the selected item is changed, the function someFunction() is getting called for infinite times (although the change is done once), what should be changed in order to make sure someFunction() get's called only once ( someFunction() is a function in the scope of the controller in which the directive is being used )

[ I did try using & and @ for the scope type of ngChange, somefunction() doesn't get fired if using those. ]

like image 913
Vishwajeet Vatharkar Avatar asked Aug 21 '15 18:08

Vishwajeet Vatharkar


1 Answers

You should use & which is used for expression and from markup you could call that method like ngChange() instead of ngChange only

Markup

  <select 
        ng-model="ngModel" ng-change="ngChange()"
        ng-options="option[optionId] as option[optionName] for option in options">
  </select>

Code

scope: {
   ngModel: '=',
   ngChange: '&'
}

Example Plunkr

like image 164
Pankaj Parkar Avatar answered Oct 30 '22 20:10

Pankaj Parkar