MesutAtasoy
MesutAtasoy

Reputation: 822

How to add object which checked in array?

I have checkboxes in the application, When I click check-box , The object which I checked, is added in array. But When I click one more time checkbox (unchecked), The object is not removed in array. How can I fix it ?

HTML Source:

<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>

Controller:

$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);
  }
};

In the function Answer include only OptionId and QuestionId.

How can I find index of {OptionId:1,QuestionId:1}?

Upvotes: 2

Views: 101

Answers (2)

jcubic
jcubic

Reputation: 66488

You can't use indexOf to find objets in array you need to iterate over array:

$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);
  }
};

Upvotes: 0

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Try like this

var index = $scope.MyAnswers.map(function(x) {
    return x.OptionId + "#" + x.QuestionId;
}).indexOf(Answer.OptionId + "#" + Answer.QuestionId);
console.log(index);

Upvotes: 1

Related Questions