1

I'm trying to print just the unique values of names but i'm unable to do that.

html code:

<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 code:

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 } },
    ];

}

the jsfiddle is here: http://jsfiddle.net/nvarun123/0tgL7u6e/73/

This code is working if i remove unique from the ng-repeat.

Varun
  • 3,695
  • 6
  • 21
  • 34

2 Answers2

2

Here you go, I used the unique filter in angular UI directives, link in the bottom. I have made a small change in the directive for implementing deep finding using string. The details are inside the references.

Here is a demo of the filter.

JSFiddle Demo

Change made inside unique filter.

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

As seen above I am implementing the deepFind function. The function is also provided below.

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;
}

References:

  1. Angular-UI unique filter

  2. Javascript get deep value by passing path

Naren Murali
  • 19,250
  • 3
  • 27
  • 54
0

Here's a simple custom filter that should meet your needs:

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)
    })
  }
});
Matthew Cawley
  • 2,688
  • 1
  • 8
  • 19