我使用的是角度1.3,但他的问题可能只与javascript有关。
我的候选人阵列:
var candidates = [
{ "attr1": "lu", "attr2": "pizza" },
{ "attr1": "gina", "attr2": "sushi" },
{ "attr1": "hed", "attr2": "hummus" }
];
我的人民阵列:
var peoples = [
{ "attr1": "bob", "attr2": "pizza" },
{ "attr1": "john", "attr2": "sushi" },
{ "attr1": "larry", "attr2": "hummus" }
];
我也有一些复选框:
<div class="checkbox" ng-repeat="d in candidates ">
<label>
<input name="d[]" type="checkbox"ng-click="addRemove(d)" ng-value="d">
{{d.attr1}}
</label>
所以我有一个切换项目的功能(来自候选人),我想添加或删除(如果已经存在)
$scope.addRemove = function (item) {
var idx = peoples.indexOf(item);
if (idx > -1) {
peoples.splice(idx, 1);
}
else {
peoples.push(item);
}
};
出于某种原因,if (idx > -1)
它永远不会是真的,即使它们已经存在,它也会不断添加项目。
答案 0 :(得分:0)
indexOf不会逐个比较对象,而是通过引用比较对象。您可以执行以下操作。
(抱歉更新了我的答案,以获得&#34; idx&#34;如果存在,则不会更新
你可以这样做:
var idx = peoples.map(function(p){ return p.attr2;}).indexOf(item.attr2);
if (idx) {
peoples.splice(idx, 1);
}
else {
peoples.push(item);
}