1

I'm pretty new in angular, so my question may looks simple or stupid, but I didn't found any solution. I have a collection in my controller (for example, a collection of integers) and I want to filter it and take items for which condition is true.

At first I tried this:

<div>{{myCollection.find(item => item === 2)}}</div>

and it didn't work. Then I found another approach (which one I don't like because I will always have only single element to show and there is no need in peretition):

<div ng-repeat="item in list | filter:{item === 2}">
    <div>{{item}}</div>
</div>

And it also doesn't work. Here is JSBin with my efforts: http://jsbin.com/govovocace/1/edit?html,js,output

Is there any possible solution of my problem? Calculating the required field in controller and passing it to the view doesn't suit me (unfortunately).

3 Answers 3

1

You had syntactical mistake. You should not be mentioning any object inside filter as you're directly filtering actual object which you are looping on. The last option true is because we are going to perform exact check.

HTML

<div ng-repeat="item in list | filter: 2: true">
    <div>{{item}}</div>
</div>

Demo Plunkr

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! It is exactly what I was looking for! I wish I had enough reputation to upvote your answer and mark it as accepted :)
I think you have it enough, Thanks ;)
1

You can define a filter function in your controller like so:

$scope.filterFn = function(val){
    return val === 2;
};

And then use it in your template like so:

<div ng-repeat="item in list | filter:filterFn">
    <div>{{item}}</div>
</div>

Tha said, this is equivalent to just filtering the array to begin with, so i'm not sure if this meets your needs or not. If you have a particular use case this doesn't suit let me know in the comments.

1 Comment

Thanks! It also works, but Pankaj's answer suits me more because I don't change controller. But thanks anyway!
0

i would have done something like this

.controller('SomeController',function($scope){

 // get the list from somewhere
  $scope.list  = [] // some array for instance

  $scope.dataList = list.filter(function(i){
     return i.someVal==list.someVal; // condition that satisfy your req
  });

});

and now use it in view as

<div ng-repeat=" item in dataList"> 
   {{item}}
</div>

if your condition will return only one result then you can do

$scope.dataList = list.filter(function(i){
         return i.someVal==list.someVal; // condition that satisfy your req
      })[0];

1 Comment

Sorry, this solution doesn't suit my case. I don't have data in $scope in controller - it adds there somewhere later, so I can't filter it inside. I know it sounds strange, but that is true.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.