1

I have problems getting length of array-elements with specified attribute using $filter. the attribute state can be 0, 1 and -1. I get sub-arrays with $filter and then check length. It wont work with state = 1. It seems that the filter also takes elements with state = -1. Is this a bug or do I need to set the filter differently?

I provided a snippet to show the effekt. Thanks in advance.

angular.module ('app', []).controller ('ctrl', function ($scope, $filter) {

  $scope.data = [
    { state: 0 },
    { state: 1 },
    { state: -1 }
  ];
  
  $scope.out1 = $filter ('filter')($scope.data, { state: 0 }).length;  // =1
  $scope.out2 = $filter ('filter')($scope.data, { state: 1 }).length;  // =2 <== THATS NOT RIGHT
  $scope.out3 = $filter ('filter')($scope.data, { state: -1 }).length; // =1
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="app" ng-controller="ctrl">

  <div>Elements with state=0 --> <strong ng-bind="out1"></strong></div>
  <div>Elements with state=1 --> <strong ng-bind="out2"></strong></div>
  <div>Elements with state=-1 --> <strong ng-bind="out3"></strong></div>

</div>

2
  • I think it treats it like a string, for example <div ng-repeat="x in data | filter:{'state':1}"> {{x}} </div> will give you states -1 and 1, both containing 1 as the filter specified. Maybe you need a custom filter, checking for the numerical values Commented Apr 9, 2018 at 8:12
  • @AlekseySolovey That is what I was thinking to. Isn't there a way to search for literal instead of containing? Commented Apr 9, 2018 at 8:46

1 Answer 1

1

AngularJS treats state values as strings("-1".indexOf("1") != -1), so just add additional third strict argument to filter:

$scope.out2 = $filter('filter')($scope.data, { state: 1 }, true).length;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! It's exactly what i was looking for. Can't believe i didn't saw that in the docs.
Would you mind upvoting my question for student-badge's sake? ;)

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.