簡體   English   中英

AngularJS:在更改select元素之前調用ng-change

[英]AngularJS: ng-change called before an select element is changed

據我所知,在select元素中實際更改ng-model之前調用ng-change 以下是重現問題的一些代碼:

 angular.module('demo', []) .controller('DemoController', function($scope) { 'use strict'; $scope.value = 'a'; $scope.displayValue = $scope.value; $scope.onValueChange = function() { $scope.displayValue = $scope.value; }; }) .directive("selector", [ function() { return { controller: function() { "use strict"; this.availableValues = ['a', 'b', 'c']; }, controllerAs: 'ctrl', scope: { ngModel: '=', ngChange: '=' }, template: '<select ng-model="ngModel" ng-change="ngChange()" ng-options="v for v in ctrl.availableValues"> </select>' }; } ]); 
 <html lang="en"> <head> <meta charset="utf-8"> </head> <body> <div ng-app="demo" ng-controller="DemoController"> <div selector ng-model="value" ng-change="onValueChange"> </div> <div> <span>Value when ng-change called:</span> <span>{{ displayValue }}</span> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script> <script src="demo.js"></script> </body> </html> 

如果你運行它,你應該改變組合框2次(例如'b'(必須不同於默認值),然后'c')。

  • 第一次,沒有任何反應(但文本中顯示的值應該已更改以匹配選擇)。
  • 第二次,該值應更改為先前的選擇(但應該已設置為當前選擇)。

這聽起來與以前幾篇文章非常類似: 在ng-changeAngularJS 之后更新了AngularJS范圍 - 為什么在模型更新之前調用ng-change? 不幸的是,我無法重現第一個問題,第二個問題是通過我已經使用的不同范圍綁定解決的。

我錯過了什么嗎? 有解決方法嗎?

最好不要在指令中使用相同的模型值。 創建另一個應該在指令內部使用的innerModel ,並在需要時使用提供的NgModelController更新“父”模型。

使用此解決方案,您不會破壞ng-change行為 - 只需使用Angular已提供的內容即可。

 angular.module('demo', []) .controller('DemoController', function($scope) { $scope.value = 'a'; $scope.displayValue = $scope.value; $scope.onValueChange = function() { $scope.displayValue = $scope.value; }; }) .directive("selector", [ function() { return { controller: function() { this.availableValues = ['a', 'b', 'c']; }, require: 'ngModel', controllerAs: 'ctrl', scope: { 'ngModel': '=' }, template: '<select ng-model="innerModel" ng-change="updateInnerModel()" ng-options="v for v in ctrl.availableValues"> </select>', link: function(scope, elem, attrs, ngModelController) { scope.innerModel = scope.ngModel; scope.updateInnerModel = function() { ngModelController.$setViewValue(scope.innerModel); }; } }; } ]); 
 <div ng-app="demo" ng-controller="DemoController"> <div selector ng-model="value" ng-change="onValueChange()"> </div> <div> <span>Value when ng-change called:</span> <span>{{ displayValue }}</span> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script> 

靈感來自這個答案

這是一個摘要問題..只需用$timeout包裝onValueChange操作:

$scope.onValueChange = function() {
   $timeout(function(){
       $scope.displayValue = $scope.value;        
   });
};
  • 不要忘記在控制器中注入$timeout

...或者您可以查看此鏈接 ,了解如何為自定義指令實施ng-change

暫無
暫無

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

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