Angular Custom Filter忽略参数

时间:2017-01-31 17:12:22

标签: javascript angularjs

我有一个自定义过滤器(arrayDiff),它接受一个参数。过滤器在ng-repeat中调用,但无论我插入什么参数,过滤器总是将整个数组作为参数。

angular.module('demo', [])
.controller('Ctrl', function ($scope, $filter) {
    $scope.selectedPriority = [ ];
    $scope.data = [];
    $scope.priorities = [1, 2, 3];
    $scope.objects = [{"date": "2017-01-08", "duration": 120}, {"date": "2017-01-08", "duration": 120}];

})

.filter('arrayDiff', function() {
    return function(diff) {
      console.log(diff); //is always [1,2,3]
        return diff;

    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="demo" ng-controller="Ctrl">

  <head>
     <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0-rc2/angular-material.min.css">
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>

  <!-- Angular Material Library -->
  <script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0-rc2/angular-material.min.js"></script>
  <div ng-repeat="object in objects">
    <input-container>
      <select ng-model="selectedPriority[$index].priority" ng-change="selectedPriority[$index].objectId = object.id" >
        <option ng-value="priority" ng-repeat="priority in priorities | arrayDiff:'hello'">{{ priority }}</option> //Filter call
      </select>
    </input-container>
  </div>
  </body>

</html>

1 个答案:

答案 0 :(得分:2)

您需要传递diff作为第二个参数,因为第一个参数始终是数组本身:

.filter('arrayDiff', function() {
    return function(array, diff) {
      console.log(diff); 
        return diff;

    };
});