我试图理解我在AngularJS中注意到的特别奇怪的行为。这是展示问题的基本代码:
(function (angular) {
var module = angular.module('test', []);
module.controller('TestCtrl', ['$scope', function ($scope) {
$scope.channels = [
{ name: 'A', id: 1, defSource: 'Y' },
{ name: 'B', id: 2 },
{ name: 'C', id: 3, defSource: 'Z' },
];
$scope.sources = [ 'X', 'Y', 'Z' ];
$scope.model = {};
$scope.channelChanged = function() {
$scope.model.source = $scope.model.channel.defSource;
};
}]);
})(angular);
angular.element(document).ready(function () {
angular.bootstrap(document, ['test']);
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<form ng-controller="TestCtrl">
<div>
<label>Channel: <select ng-model="model.channel"
ng-options="channel.name for channel in channels"
ng-change="channelChanged()"></select></label>
</div>
<div>
<label>Source: <select ng-model="model.source"
ng-options="source for source in sources"></select></label>
</div>
<br />
<div>Channel = {{model.channel}}</div>
<div>Source = {{model.source}}</div>
</form>
&#13;
观察到的行为(使用Chrome)是这样的:
在所有情况下,模型中的值都是正确的;它只是最终表现出色的用户界面。
我可以通过明确提供<option>
元素来表示源代码中的null来解决这个问题,但我不明白为什么这段代码有这种行为,特别是对于&#的两种不同行为34; C&#34;取决于先前的选择,以及为什么&#34; A&#34;并没有做同样的事情。这是一个已知的AngularJS或Chrome错误,还是我错过了什么?
答案 0 :(得分:0)
这是您正在使用的Angular版本中的错误。请尝试使用1.3
的最新版本1.3.17
。
(function (angular) {
var module = angular.module('test', []);
module.controller('TestCtrl', ['$scope', function ($scope) {
$scope.channels = [
{ name: 'A', id: 1, defSource: 'Y' },
{ name: 'B', id: 2 },
{ name: 'C', id: 3, defSource: 'Z' },
];
$scope.sources = [ 'X', 'Y', 'Z' ];
$scope.model = {};
$scope.channelChanged = function() {
$scope.model.source = $scope.model.channel.defSource;
};
}]);
})(angular);
angular.element(document).ready(function () {
angular.bootstrap(document, ['test']);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.17/angular.min.js"></script>
<form ng-controller="TestCtrl">
<div>
<label>Channel: <select ng-model="model.channel"
ng-options="channel.name for channel in channels"
ng-change="channelChanged()"></select></label>
</div>
<div>
<label>Source: <select ng-model="model.source"
ng-options="source for source in sources"></select></label>
</div>
<br />
<div>Channel = {{model.channel}}</div>
<div>Source = {{model.source}}</div>
</form>
&#13;