【发布时间】:2017-06-16 05:40:04
【问题描述】:
我有一个基于数组的 ngOptions 选择。这个数组可以改变。
如果新数组值不包含选定的选项值,则选项值由 selectController 设置为 undefined。有没有办法防止这种情况发生?
Plunker:https://plnkr.co/edit/kao3h5ivHXlP1Wrdx1Ib?p=preview
场景:
- 选择蓝色/红色或绿色
- 点击缩小为只有黑白选项
- 看到模型值留空
想要的行为:模型值保持在蓝色/红色或绿色
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
</head>
<body ng-app="selectExample">
<script>
angular.module('selectExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.colorsFull = [
{id:"bk", name:'black'},
{id:"w", name:'white'},
{id:"r", name:'red'},
{id:"be", name:'blue'},
{id:"y", name:'yellow'}
];
$scope.colors = $scope.colorsFull;
$scope.selectedColor =$scope.colorsFull[0];
$scope.colorsReduced = [
{id:"bk", name:'black2'},
{id:"w", name:'white2'}];
}]);
</script>
<div ng-controller="ExampleController">
<button ng-click="colors=colorsReduced">Reduced</button>
<button ng-click="colors=colorsFull">Full</button>
<br/>
Colors : {{colors}}
<hr/>
<select ng-model="selectedColor" ng-options="color.name for color in colors track by color.id">
</select>
selectedColor:{{selectedColor}}
</div>
</body>
</html>
【问题讨论】:
-
好吧,我打赌这个对象被设置为未定义,所以它没有什么可追踪的。当你点击减少的颜色时,我会调用一个函数,然后将你的颜色设置为某种空白颜色,我不会处理 html 代码,我会在控制器中处理它......你能有颜色是'空白”
-
我敢打赌它试图通过 id 找到新颜色,并且该 id 已被删除,因此它发现未定义......
标签: angularjs