0

I have an empty array that I'm just pushing integers into. However, the console.logs print am empty array [ ] everytime I trigger this function in my view:

html:

<div ng-repeat="color in colors">
  {{color.name}} <input type="checkbox" ng-model="color_ids" ng-change="toggleColorFilter(color.id)">
</div>

angular:

app.controller('IndexCtrl', ['$scope', "Product", "Color", function($scope, Product, Color) {

  ...
  $scope.color_ids = [];


  $scope.toggleColorFilter = function(color_id) {
    var index = $scope.color_ids.indexOf(color_id);
    if (index > -1) {
      $scope.color_ids.push(color_id);
    } else {
      $scope.color_ids.splice(index, 1);
    }
    console.log($scope.color_ids);
  };


}]);

1 Answer 1

1

Your if logic is backwards - it's saying that if the color id exists - then push it, else, splice a non-existent value...flip the logic:

if (index > -1) {
  $scope.color_ids.splice(index, 1);
} else {
  $scope.color_ids.push(color_id);
}
Sign up to request clarification or add additional context in comments.

3 Comments

It worked!! but why? If the index is -1 that means it exists in the array??
If the index is greater than -1 - it exists - so you want to splice it. If the index equals -1 it doesnt exist.
... how did I miss that. I need to step away from the computer for a few minutes. thanks!!

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.