Angular js,Unique过滤器不起作用

时间:2015-03-23 15:30:20

标签: angularjs angularjs-ng-repeat angular-ui

我尝试将复选框过滤器应用于列表,但复选框的选项也应仅列在项目列表中, 如果我为所有复选框迭代它,它工作正常, 当我尝试应用唯一过滤器来显示复选框选项时,问题就出现了。 我已经包括在内 角1.4和ui-utils

<script src="js/angular.min.js"></script>
<script src="js/ui-utils.min.js"></script>

我的视图和控制器定义为:

<div ng-controller="Test">
    <div ng-repeat="person in persons | unique:type">
      <!-- record that this person has been selected -->
      <input type="checkbox" ng-checked="person.checked" ng-model="person.checked" /> {{ person.type }}
    </div>
  <ul>
    <li ng-repeat="person in persons | selectedTypes">{{person.name}}</li>
  </ul>
</div>

和脚本是

<script>
    var app = angular.module("MyApp", ['ui.utils']);
    app.controller("Test", function($scope) {
      $scope.persons = [
        { type: 1,   name: 'Ankit Balyan' },
        { type: 1,   name: 'Abhilaksh' },
        { type: 2,   name: 'Sanket Srivastav' },
        { type: 2,   name: 'Sachin Sharma' },
        { type: 2,   name: 'Rohan Rathor' },
        { type: 2,   name: 'Jim' },
      ];

        $scope.$watch('persons', function() {
            console.log($scope.persons);
        })
    });

// Define our filter
app.filter('selectedTypes', function($filter) {
  return function(persons) {
    var i, len;

    // get persons that have been checked
    var checkedPersons = $filter('filter')(persons, {checked: true});
    // Add in a check to see if any persons were selected. If none, return 
    // them all without filters
    if(checkedPersons.length == 0) {
      return persons;
    }
    //console.log(checkedPersons);
    // get all the unique cities that come from these checked persons
    var types = {};
    for(i = 0, len = checkedPersons.length; i < len; ++i) {
      // if this checked persons cities isn't already in the cities object 
      // add it
      if(!types.hasOwnProperty(checkedPersons[i].type)) {
        types[checkedPersons[i].type] = true;
      }
    }
    // Now that we have the cities that come from the checked persons, we can
    //get all persons from those cities and return them
    var ret = [];
    for(i = 0, len = persons.length; i < len; ++i) {
      // If this person's city exists in the cities object, add it to the 
      // return array
      if(types[persons[i].type]) {
        ret.push(persons[i]);
      } 
    }
    //console.log(persons.length);
    // we have our result!
    return ret;
  };
});
</script>

1 个答案:

答案 0 :(得分:1)

您必须将属性的名称作为字符串:

<div ng-repeat="person in persons | unique: 'type'">

而不是

<div ng-repeat="person in persons | unique: type">

修改:如果您没有提供引号,则应用变量type的值来应用唯一的过滤器,而不是在你的情况下定义,因此过滤器没有效果。