簡體   English   中英

如何為選擇列表的自定義指令實現ng-change?

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

我的指令用法代碼

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

我的指令代碼

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

我的指令模板

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

因此,當更改所選項時,函數someFunction()將被無限次調用(盡管更改只執行一次),應該更改為了確保someFunction()只被調用一次( someFunction()是在使用該指令的控制器范圍內的函數)

[我確實嘗試使用&@作為ngChange的范圍類型,如果使用那些函數,則somefunction()不會被觸發。 ]

您應該使用&用於表達式,並且從標記開始,您可以像ngChange()而不是ngChange一樣調用該方法

標記

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

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

示例Plunkr

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM