簡體   English   中英

角度:選擇以編程方式更改ng-model,但不會觸發ng-change事件

[英]Angular: select ng-model programmatically changed but ng-change event doesn't fire

這是我的選擇元素:

 <select class="small-3 columns end statSelect"
          ng-model="chart.categoryAxis"
          ng-change="renderMainChart()"
          ng-options="metric as metric.value for metric in chart.metrics()">
  </select>

每次單擊按鈕時,我都會以編程方式更改chart.categoryAxis。 但是,不會調用ng-change方法renderMainChart()。 為什么是這樣?

這是其中一個選項的示例:

<option label="Ad Started" value="object:33">Ad Started</option>

根據我單擊的按鈕,相應地更改ng-model值。 但是ng-change函數renderMainChart()沒有被調用。

Aelliott1485的答案可以實現,但需要您添加一塊額外的手表,但這可能並不總是可取的。


如果您使用的是Angular 1.3或更高版本,則可以將函數傳遞給ng-model指令。

這使您可以在ng-model屬性中指定方法而不是變量。 該方法應采用可選參數。 如果傳遞了參數,則應存儲該值;如果不傳遞參數,則應返回一個值。

在這種情況下,將您的ng-model更改為調用函數而不是訪問屬性。

<select class="small-3 columns end statSelect"
      ng-model="chart.categoryAxis()"
      ng-change="renderMainChart()"
      ng-options="metric as metric.value for metric in chart.metrics()">    
</select>

並在控制器中編寫這樣的函數

$scope.categoryAxis = function(value) {
    $scope.ca = value || $scope.ca; // You can also keep a local variable inside the controller instead of a property on $scope
    return $scope.ca;
};

注意:您可能需要提出更好的名稱。

您可以利用$ watch()處理值的更改,即使用戶沒有使用選擇列表來更改值也是如此。 例如:

 var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { var options = [{ value: 'a', id: 1 }, { value: 'b', id: 2 }]; $scope.debugOutput = ''; $scope.chart = { categoryAxis: options[0], metrics: function() { return options; } }; $scope.renderMainChart = function() { console.log('renderMainChart', arguments); }; $scope.pickA = function() { $scope.chart.categoryAxis = options[0]; }; $scope.pickB = function() { $scope.chart.categoryAxis = options[1]; }; $scope.$watch('chart.categoryAxis', function(newValue, oldValue) { $scope.debugOutput += 'categoryAxis changed ' + angular.toJson(oldValue) + ' to ' + angular.toJson(newValue) + "\\n"; }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="plunker"> <div ng-controller="MainCtrl"> <select class="small-3 columns end statSelect" ng-model="chart.categoryAxis" ng-change="renderMainChart()" ng-options="metric as metric.value for metric in chart.metrics()"></select> <div>Selected category Axis: <span>{{ chart.categoryAxis | json }}</span></div> <div> <input type="button" ng-click="pickA()" value="pickA" /> </div> <div> <input type="button" ng-click="pickB()" value="pickB" /> </div> <div>{{ debugOutput }}</div> </div> </div> 

暫無
暫無

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

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