简体   繁体   English

如何在ng-repeat过滤器中使用作用域变量?

[英]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. 我完全确定我会以错误的方式进行操作,但是看到我对angularjs的了解是多么新,我无法弄清楚如何完成我想要的。 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 . 我有一组正在使用ng-repeat查找的用户,但是我不知道如何通过范围变量userId进行过滤。 The User id: <name> is being printed out just fine, so there is no issues with the scope. 可以很好地打印出User id: <name> ,因此作用域没有问题。 How can I have the ng-repeat loop sort by this userId ? 如何通过此userId进行ng-repeat循环排序? 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: 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;
}

You can simply use a $scope variable userId in ng-repeat like so 您可以像这样在ng-repeat中简单地使用$scope变量userId

<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 确切地使用双花括号,单花括号和无花括号时

If the structure of users is like this: 如果users的结构是这样的:

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

You can use the 'orderBy' filter to sort it and use filter filter to filter it: 您可以使用“ orderBy”过滤器对其进行排序,并使用filter器过滤器对其进行过滤:

<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 . idng-repeatuser的属性。

And here are the documentations: filter and orderBy 这里是文档: filterorderBy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM