2017-09-13 59 views
0

我想打印名稱的唯一值,但我無法做到這一點。AngularJS ng-repeat獨特不起作用

的html代碼:

<div ng-controller="MyCtrl"> 
    <div><input type="text" ng-model="nameFilter" placeholder="Search..." /></div> 
    <p ng-repeat="contact in contacts | orderBy: 'customer.name'| unique:'customer.name'">{{ contact.customer.name }}</p> 


</div> 

JS代碼:

var myApp = angular.module('myApp',[]); 

function MyCtrl($scope) { 
    $scope.nameFilter = ''; 
    $scope.contacts = [ 
     { id:1, customer: { name: 'foo', id: 10 } }, 
     { id:2, customer: { name: 'bar', id: 20 } }, 
     { id:3, customer: { name: 'foo', id: 10 } }, 
     { id:4, customer: { name: 'bar', id: 20 } }, 
     { id:5, customer: { name: 'baz', id: 30 } }, 
     { id:5, customer: { name: 'tar', id: 30 } }, 
     { id:5, customer: { name: 'got', id: 30 } }, 
     { id:5, customer: { name: 'man', id: 30 } }, 
     { id:5, customer: { name: 'baz', id: 30 } }, 
    ]; 

} 

中的jsfiddle是在這裏:http://jsfiddle.net/nvarun123/0tgL7u6e/73/

此代碼工作,如果我刪除從納克重複獨特。

+0

您的代碼缺少'unique'自定義過濾器。這不是內置的過濾器之一,所以你必須自己寫。 –

+0

認爲獨特的過濾器已經在angularjs中定義了 – Varun

+1

恐怕不是,[這些是內置的過濾器](https://docs.angularjs.org/api/ng/filter) –

回答

1

在這裏,我使用unique過濾器在角度UI指令,鏈接在底部。我在實施deep finding using string的指令中做了一些小改動。細節在參考文獻中。

下面是過濾器的演示。

JSFiddle Demo

更改內部unique過濾製成。

var extractValueToCompare = function (item) { 
     if (angular.isObject(item) && angular.isString(filterOn)) { 
      return deepFind(item,filterOn); 
     } else { 
      return item; 
     } 
     }; 

如上所示,我正在執行deepFind函數。該功能也在下面提供。

function deepFind(obj, path) { 
    var paths = path.split('.') 
    , current = obj 
    , i; 

    for (i = 0; i < paths.length; ++i) { 
    if (current[paths[i]] == undefined) { 
     return undefined; 
    } else { 
     current = current[paths[i]]; 
    } 
    } 
    return current; 
} 

參考文獻:

  1. Angular-UI unique filter

  2. Javascript get deep value by passing path

0

這裏是一個要滿足您的需要一個簡單的自定義過濾器:

app.filter("unique", function thisFilter() { 
    return function(input){ 
    var seen = { objectNames: [] }; 
    return input.filter(function(obj){ 
     return !seen.objectNames.includes(obj.customer.name) 
     && seen.objectNames.push(obj.customer.name) 
    }) 
    } 
}); 
0

利用軌跡由$指數

<p ng-repeat="contact in contacts track by $index| orderBy: 'customer.name' 
    ">{{ contact.customer.name }}</p>