我在应用程序中有复选框,当我单击复选框时,我检查的对象被添加到数组中。但是,当我再次单击复选框(未选中)时,该对象不会在数组中删除。 我该如何解决?
HTML来源:
<ion-list ng-repeat="option in question.SurveyOptions ">
<li class="item item-checkbox checkbox-royal ">
<label class="checkbox">
<input type="checkbox" ng-checked="MyAnswers.indexOf(option)!=-1" ng-click="toggleCheckAnswer({OptionId:option.Id,QuestionId:question.Id})">
</label>
<div class="item item-text-wrap">
{{option.OptionsName}}
</div>
</li>
</ion-list>
控制器:
$scope.MyAnswers = [];
$scope.toggleCheckAnswer = function(Answer) {
if ($scope.MyAnswers.indexOf(Answer) === -1) {
$scope.MyAnswers.push(Answer);
} else {
$scope.MyAnswers.splice($scope.MyAnswers.indexOf(Answer), 1);
}
};
在功能中,答案仅包括OptionId和QuestionId。
如何找到{OptionId:1,QuestionId:1}
的索引?
答案 0 :(得分:1)
试试这个
var index = $scope.MyAnswers.map(function(x) {
return x.OptionId + "#" + x.QuestionId;
}).indexOf(Answer.OptionId + "#" + Answer.QuestionId);
console.log(index);
答案 1 :(得分:0)
您无法使用indexOf查找需要迭代数组的数组中的objets:
$scope.toggleCheckAnswer=function(Answer) {
var index = -1;
for (var i=0; i<$scope.MyAnswers.length; ++i) {
var answer = $scope.MyAnswers[i];
if ($scope.MyAnswers[i].OptionId == Answer.OptionId &&
$scope.MyAnswers[i].QuestionId == Answer.QuestionId) {
index = 1;
break;
}
}
if (index === -1) {
$scope.MyAnswers.push(Answer);
} else {
$scope.MyAnswers.splice(index, 1);
}
};