最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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. ]

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. ]

Share Improve this question edited Aug 21, 2015 at 18:59 Pankaj Parkar 136k23 gold badges240 silver badges303 bronze badges asked Aug 21, 2015 at 18:26 Vishwajeet VatharkarVishwajeet Vatharkar 1,2065 gold badges20 silver badges42 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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

发布评论

评论列表(0)

  1. 暂无评论