【问题标题】:AngularJS unique filter not workingAngularJS独特的过滤器不起作用
【发布时间】:2016-06-10 14:07:04
【问题描述】:

我有以下代码,但无法使用unique 过滤器。

同样在 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>

【问题讨论】:

  • jsFiddle 有 angularjs 的问题,在 plunker 中试试。
  • 它应该如何工作:jsbin.com/lepuxapoxe/edit?html,js,output - 我觉得很好
  • 现在是这样工作的,但我希望那个唯一的处于活动状态,这样 Atena 只会在选择中显示一次。
  • 您是否正确包含了 Angular ui 唯一过滤器?

标签: javascript angularjs filter unique


【解决方案1】:

据我所知,唯一的过滤器需要从另一个模块“ui.filters”中调用。

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

【讨论】:

    【解决方案2】:

    我 fork 你的 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}}">
    

    【讨论】:

    • 谢谢你这是我想要的。
    猜你喜欢
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多