簡體   English   中英

ngRepeat按deep屬性過濾

[英]ngRepeat Filter by deep property

如果我有一個以對象作為屬性值的復雜對象,如何按嵌套的屬性之一進行過濾?

可以使用OOB ng-repeat過濾器完成此操作嗎?

數據

{
  Name: 'John Smith',
  Manager: {
     id: 123,
     Name: 'Bill Lumburg'
  }
}

ngRepeat

<li ng-repeat="e in emps | filter:Manager.Name">{{ e.Name }}</li>

您需要傳遞參數以過濾:

<input ng-model="filter.key">
<ul>
  <li ng-repeat="e in list | filter: {Manager: {Name: filter.key}}">
    {{e.Name}}  (Manager: {{e.Manager.Name}})
  </li>
</ul>

柱塞示例

如果要過濾多個屬性,則語法將類似於以下內容。

<ul>
  <li ng-repeat="item in list | {filter: top_object_property_name: value, top_object_property_with_nested_objects_name: {nested_object_property_name: value}}">
       ...
  </li>
</ul>

例如:

        var employees = [name: 'John', roles: [{roleName: 'Manager'},{roleName: 'Supervisor'}]];

        <li ng-repeat="staff in employees | {filter: name: 'John', roles: {roleName: 'Manager'}}">
              ...
        </li>

在最新版本的angularjs中,嵌套obj過濾器默認實現。可以正常使用過濾器。 僅適用於角度1

要使用多個深度屬性進行過濾,我們需要創建自定義過濾器。 我的意思是我們需要創建自己的函數來過濾對象中的數據並返回所需的對象(已過濾的對象)。

例如我需要從下面的對象過濾數據-

[
{
   "document":{
      "documentid":"1",
      "documenttitle":"test 1",
      "documentdescription":"abcdef"
       }
},
{
   "document":{
      "documentid":"2",
      "documenttitle":"dfjhkjhf",
      "documentdescription":"dfhjshfjdhsj"
       }
}
]

在HTML中,我們使用ng-repeat來顯示文檔列表-

<div>
   //search input textbox
   <input ng-model="searchDocument" placeholder="Search">
 </div>
<div ng-repeat="document in documentList | filter: filteredDocument">
   //our html code 
</div>

在Controller中,我們編寫過濾器函數以使用對象的兩個屬性“ documenttitle”和“ documentdescription”返回過濾后的對象,代碼示例如下-

function filterDocuments(document)
        {
            if($scope.searchDocument)
            {
                     if(document.documentTitle.toLowerCase().indexOf($scope.searchDocument.toLowerCase()) !== -1 || document.document.shortDescription.toLowerCase().indexOf($scope.searchDocument.toLowerCase()) !== -1)
                {
                    //returns filtered object
                    return document
                }
            }else {
               return document;
            }
        }

其中$ scope.searchDocument是綁定到搜索文本框(HTML輸入標簽)的范圍變量,用戶可以在其中輸入要搜索的文本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM