AngularJS filter with multiple perms

依然范特西╮ 提交于 2020-01-05 08:46:25

问题


i have a users like this

[{id:1,name:'name',parent_id:0,type:1},
{id:2,name:'name2',parent_id:0,type:2},
{id:3,name:"name1 child",parent_id:1,type:1}]

and i am trying to display parents and child users based on parent_id and type id so for example id 3 is child of id 1 and i am trying to display them like this

http://jsfiddle.net/U3pVM/689/

thanks for help


回答1:


I fixed up your fiddle:

http://jsfiddle.net/eQP8S/

 <div ng-controller="MyCtrl">
    <ol>
    <li ng-repeat="user in users | filter:{parent_id:0}">
         {{user.name}}
        <ol>
               <li ng-repeat="child in users | filter:{parent_id:user.id, type:user.type}">
                   {{child.name}}
               </li>
        </ol>
    </li>
   </ol>
</div>

Your main problem was that you were trying to use the "filter" filter with a function, which is okay, but that function isn't allowed to take any parameters. If you actually need to create a filter that takes parameters you have to write a custom filter: http://docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters.

But in your case, you can use the standard "filter" filter and pass it objects that will do what you want.

Also, curse you Angular developers for creating an abstraction called filter and then creating a "filter" filter. I mean, how confusing is that?




回答2:


That is not the correct way to use filters. If you check the documentation, you have three options:

  1. use a string. It will be searched deeply in the object. Any object with some deep value containing the string will match
  2. use a function. It will be called for elements of the array. You should provide any parameter in the function's scope, not as a parameter to the filter.
  3. use an object. It will work like the string match, but for specific properties.

If you use the third case

<li ng-repeat="child in users | filter:{parent_id: user.id, type: user.type}">

and moreover print the child's name

{{ child.name }}

then you'll see the correct results.

http://jsfiddle.net/waAc7/



来源:https://stackoverflow.com/questions/16926823/angularjs-filter-with-multiple-perms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!