据我所知,ng-change
是在 ng-model
在 select
元素中实际更改之前调用的。下面是一些重现问题的代码:
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')。
- 第一次没有任何反应(但文本中显示的值应该已更改以匹配选择)。
- 第二次,值应该更改为之前的选择(但应该设置为当前选择)。
这听起来与之前的几篇文章非常相似:AngularJS scope updated after ng-change和 AngularJS - Why is ng-change called before the model is updated? .不幸的是,我无法重现第一个问题,第二个问题已通过我已经在使用的不同范围绑定(bind)解决。
我错过了什么吗?有解决方法吗?
最佳答案
最好不要在指令中使用相同的模型值。创建另一个应在指令内部使用的 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>
灵感来自 this answer .
关于javascript - AngularJS:在更改选择元素之前调用 ng-change,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34036139/