2

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

2 Answers 2

1

Try like this

var index = $scope.MyAnswers.map(function(x) {
    return x.OptionId + "#" + x.QuestionId;
}).indexOf(Answer.OptionId + "#" + Answer.QuestionId);
console.log(index);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.