2016-06-10 91 views
-1

我有以下代码,我不能让它与unique过滤器一起使用。AngularJS独特的过滤器不工作

另外在jsfiddle它不工作。在我的HTML中,select已填充,但unique过滤器不起作用。

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

谢谢

<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> 
+0

jsFiddle有一个angularjs的问题,请在plunker中尝试。 – Ohjay44

+1

这是它应该如何工作:http://jsbin.com/lepuxapoxe/edit?html,js,output - 对我来说这似乎很好 – Und3rTow

+0

现在是这样工作,但我希望独特的活动,以便Atena将在选择中只显示一次。 – Krayzie

回答

1

我叉你的jsfiddle here

你需要创建一个这样的自定义过滤器:

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

而且使用这样的:

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

谢谢,这是我想要的whant。 – Krayzie

3

据我所知,独特的过滤器需要从另一个模块'ui.filters'调用。

对不起,如果我的英语不是帽子好。