我正在使用AngularJS版本1.4.7
并且拥有包含对象数组的简单AngularJS控制器。我希望将这些对象显示为ngOptions
选择的选项。
问题是每个对象都是重复的,我不知道为什么。此副本仅在选择中显示,源对象看起来很好。
angular
.module('demo', [])
.controller('DemoCtrl', DemoCtrl);
function DemoCtrl() {
var vm = this;
vm.demoOptions = [
{value: 1, label: 'Demo 1'},
{value: 2, label: 'Demo 2'},
{value: 3, label: 'Demo 3'}
];
vm.selected = null;;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
<div ng-app="demo" ng-controller="DemoCtrl as vm">
<select ng-options="item as item.label for item in vm.demoOptions track by item.value" ng-model="vm.selected">
<option value="" selected ng-if="vm.selected === null">-- select --</option>
</select>
<p ng-if="vm.selected !== null">Selected item: <code>{{vm.selected}}</code></p>
<p ng-if="vm.selected === null">No item is selected.</p>
<pre>vm.demoOptions == {{vm.demoOptions|json}}</pre>
</div>
这是一个错误吗?如何在不使用过滤器的情况下删除重复项?
注意:将AngularJS从版本1.3.19
更新到1.4.7
后出现此问题。我阅读了更改日志,但它只讲述了track by
的添加内容 - 我添加了它但没有效果。
答案 0 :(得分:2)
这是1.4.8之前1.4.x的已知错误,您可以查看issue。
如果您必须使用angularjs 1.4.7版本,那么您可以使用ng-show
代替ng-if
您可以在angularjs github
中找到更改日志和错误答案 1 :(得分:1)
angular
.module('demo', [])
.controller('DemoCtrl', DemoCtrl);
function DemoCtrl($scope) {
var vm = this;
vm.demoOptions = [
{value: null, label: '--select--'},
{value: 1, label: 'Demo 1'},
{value: 2, label: 'Demo 2'},
{value: 3, label: 'Demo 3'}
];
vm.selected = vm.demoOptions[0];
$scope.$watch(function(){ return vm.selected}, function(newVal, oldVal){
if(!oldVal.value && newVal.value) {
vm.demoOptions.shift();
}
});
vm.setSelected = function(){
}
}
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
<div ng-app="demo" ng-controller="DemoCtrl as vm">
<select ng-options="item.label for item in vm.demoOptions" ng-model="vm.selected" ng-change="vm.setSelected()">
</select>
<p ng-if="vm.selected !== null">Selected item: <code>{{vm.selected}}</code></p>
<p ng-if="vm.selected === null">No item is selected.</p>
<pre>vm.demoOptions == {{vm.demoOptions|json}}</pre>
</div>
答案 2 :(得分:0)
您必须从<option>
字段中删除<select>
标记。因为其中的所有内容都将用于每个项目,<option>
标记本身是通过angularJS的指令生成的。
angular
.module('demo', [])
.controller('DemoCtrl', DemoCtrl);
function DemoCtrl() {
var vm = this;
vm.demoOptions = [
{value: 1, label: 'Demo 1'},
{value: 2, label: 'Demo 2'},
{value: 3, label: 'Demo 3'}
];
vm.selected = null;;
}
&#13;
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
<div ng-app="demo" ng-controller="DemoCtrl as vm">
<select ng-options="item as item.label for item in vm.demoOptions track by item.value" ng-model="vm.selected" ng-change="vm.setSelected()">
</select>
<p ng-if="vm.selected !== null">Selected item: <code>{{vm.selected}}</code></p>
<p ng-if="vm.selected === null">No item is selected.</p>
<pre>vm.demoOptions == {{vm.demoOptions|json}}</pre>
</div>
&#13;
答案 3 :(得分:0)
如果您在1.4.8或更高版本中遇到此问题,原因可能是this bug。使用$compile
时可以创建重复项。错误页面上有一些解决方法。