'ng-repeat' How to get the `unique` values
Asked Answered
L

4

12

Using an array, I am trying to filter and show the unique information in the list. For that I use the angular inbuild filter method.

But I am getting error.

Here is my try (I am filtering by SubProjectName)

<ul>
    <li ng-repeat="project in projectNames | unique: 'SubProjectName' ">
        {project.SubProjectName}}
    </li>
</ul>

Live Demo

Lumberyard answered 29/9, 2015 at 11:41 Comment(3)
Angular's built in filter does not have a unique method.Oilcloth
is it so.. then what would be the way to get it done? any one suggest me?Lumberyard
#15915158Flagrant
O
20

AngularJS doesn't include a unique filter by default. You can use the one from angular-filter. Just include the JavaScript

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.8/angular-filter.min.js"></script>

and include the dependeny in your app:

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

Your code should work right away! I edited your Plunker so it works.

Oilcloth answered 29/9, 2015 at 11:52 Comment(0)
R
6

I think you are looking for an answer like this

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

app.controller('MainCtrl', function($scope) {
  $scope.projectNames=projects
  $scope.Id = "1";
  $scope.SubProjectName="Retail Building";

})
.filter('unique', function() {
  return function(projects, subProjectName) {
    var newprojects =[];
    projects.forEach(function(project){
      if(project.SubProjectName === subProjectName)
        newprojects.push(project);
    });
    return newprojects;
  };
});

<li ng-repeat="project in projectNames | unique:SubProjectName">{{project.SubProjectName}}</li>

Demo

Ridley answered 29/9, 2015 at 12:24 Comment(1)
It is nice to do this instead of adding another package to do the same functionalitySituate
T
3

The unique filter you are probably attempting to use comes from AngularUI, so you need to include it:

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui/0.4.0/angular-ui.js"></script>

and add it as module dependency:

var app = angular.module('plunker', ['ui.filters']);
Teeth answered 29/9, 2015 at 11:47 Comment(0)
S
1

I have updated your plunkr as http://plnkr.co/edit/sx3u1ukH9752oR1Jfx6R?p=preview added filter dependency

var app = angular.module('plunker', ['angular.filter']);

Hope this may help you

Sophistry answered 29/9, 2015 at 11:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.