Krayzie Krayzie - 5 months ago 54
AngularJS Question

AngularJS unique filter not working

I have the following code and I cant get it to work with

unique
filter.

Also on jsfiddle it isn't working. In my HTML, the
select
is populated but
unique
filter is not working.

https://jsfiddle.net/krayziekry/sw8dvy3u/

Thank you

<div ng-app="example" ng-controller="exampleCtrl">
<!-- Select Basic -->
<div class="form-group span6">
<label class="control-label" for="from">Calatorind de la</label>
<div>
<select id="from" name="from" class="form-control" ng-model="selected.valp">
<option value="">Selecteaza...</option>
<option ng-repeat="rec in myRecs | filter: {vals: selected.vals} | orderBy:'plecare' | unique: 'plecare'" value="{{rec.valp}}">{{rec.plecare}}</option>
</select>
</div>
</div>
<!-- Select Basic -->
<div class="form-group span6">
<label class="control-label" for="to">catre</label>
<div>
<select id="to" name="to" class="form-control" ng-model="selected.vals">
<option value="">Selecteaza...</option>
<option ng-repeat="rec in myRecs | filter: {valp: selected.valp} | orderBy:'plecare'" value="{{rec.vals}}">{{rec.sosire}}</option>
</select>
</div>
</div>
</div>

<script>
angular.module('example', []).controller('exampleCtrl', function($scope) {

$scope.myRecs = [{
valp: 'AHO',
plecare: 'Alghero (AHO)',
sosire: 'Torino - Caselle (TRN)',
vals: 'TRN'
}, {
valp: 'ATH',
plecare: 'Atena (ATH)',
sosire: 'Constanta (CMD)',
vals: 'CMD'
}, {
valp: 'ATH',
plecare: 'Atena (ATH)',
sosire: 'Larnaca (LCA)',
vals: 'LCA'
}, {
valp: 'ATH',
plecare: 'Atena (ATH)',
sosire: 'Londra - Luton (LTN)',
vals: 'LTN'
}];
});
</script>

Answer

I forked your jsfiddle here

You will need to create a custom filter like this:

.filter('unique', function() {
    return function(collection, keyname) {
       var output = [],
       keys = [];
       angular.forEach(collection, function(item) {
          var key = item[keyname];
          if (keys.indexOf(key) === -1) {
             keys.push(key);
             output.push(item);
        }
      });
      return output;
   };
})

And use it like this:

<option ng-repeat="rec in myRecs | unique: 'valp' | orderBy:'plecare'" value="{{rec.valp}}">
Comments