2016-06-10 90 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'調用。

對不起,如果我的英語不是帽子好。