Ducksauce88
Ducksauce88

Reputation: 650

How do I use a scope variable in ng-repeat filter?

I'm entirely sure I'm going about this the wrong way but seeing how new I am with angularjs I can't figure out how to accomplish what I want. I have a set of users that I am loping through using ng-repeat, but I can't figure out how to filter by the scope variable userId. The User id: <name> is being printed out just fine, so there is no issues with the scope. How can I have the ng-repeat loop sort by this userId? If I'm going about it the wrong what, can you please link me documentation that will help me go about it the right way.

HTML:

User id: {{userId}}
<br>
User Name:
<ul>
    <li ng-repeat="user in users | filter:{{userId}}">
        {{user.name}}
    </li>
</ul>

Controller:

function PhoneDetailController($scope, $routeParams, Users){
     $scope.userId = $routeParams.userId;
}

Upvotes: 1

Views: 1398

Answers (2)

Nikhil Nanjappa
Nikhil Nanjappa

Reputation: 6632

You can simply use a $scope variable userId in ng-repeat like so

<ul>
    <li ng-repeat="user in users | filter:userId">
        {{user.name}}
    </li>
</ul>

Basically just no need of angular expressions {{}} since it is already inside an expression.

Couple of links to help you out if you need.

Here is a blog explaining Two Thumb Rules when deciding whether or not to use curlies.

When exactly to use double curly braces, single curly braces and no braces

Upvotes: 2

awmleer
awmleer

Reputation: 1800

If the structure of users is like this:

[
    {id:1,name:'xxx'},
    {id:2,name:'yyy'}
]

You can use the 'orderBy' filter to sort it and use filter filter to filter it:

<ul>
    <li ng-repeat="user in users | filter:{id:userId} | orderBy: 'id' ">
        {{user.name}}
    </li>
</ul>

id is a property of user in ng-repeat.

And here are the documentations: filter and orderBy

Upvotes: 0

Related Questions