【问题标题】:Error with range filter范围过滤器错误
【发布时间】:2016-01-19 20:43:59
【问题描述】:

我有一个名为 items 的数组,我试图通过一系列项目进行 ng-repeat,例如 0-4 或 5-11 等。所以我尝试创建自己的自定义过滤器,但目前是只显示所有数组元素。有更多知识的人可以看看它。
html

<div ng-app='myApp' ng-controller="Main">
  <li ng-repeat="item in items | filter:range(0,2)">test {{item}}</li>
</div>

过滤器

var myApp = angular.module('myApp', []);
myApp.controller('Main', function($scope, $http) {
  $scope.items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
  $scope.range = function(min, max, step) {
    return function(items) {
      var arr = $scope.items;
      step = step || 1;
      var input = [];
      for (var i = min; i <= max; i += step) {
        if (arr[i] != null) {
          input.push(arr[i]);
        }
      }
      return items = input;
    };
  };
});

结果

test 1
test 2
test 3
test 4
test 5
test 6
test 7
test 8
test 9
test 0

【问题讨论】:

    标签: javascript arrays angularjs filter ng-repeat


    【解决方案1】:

    如果您在 Angular 中创建过滤器函数,如果给定项目应该是结果集的一部分,则此函数必须返回“true”,否则返回“false”。 您的函数由于某种原因返回“items = input;”这在这种情况下没有任何意义,并且总是解析为 true-ish,这就是为什么要显示所有项目的原因。 你可以尝试类似

    $scope.range = function(min, max) {
        return function(item) {
            var i = $scope.items.indexOf (item); 
            return (i >= min && i <= max);
        };
      };
    

    请参阅角度过滤器文档以了解如何使用此功能

    【讨论】:

    • var myApp = angular.module('myApp', []); myApp.controller('Main', function($scope, $http) { $scope.items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; $scope.range = function (min, max) { return function(item) { var i = $scope.items.indexOf (item); return (i >= min+1 && i
    【解决方案2】:

    与其大惊小怪,不如使用简单的ng-if 和ng-repeat,如下所示

    <li ng-repeat="item in items" ng-if="$index >= 2 && $index <=5">test {{item}}</li>
    

    【讨论】:

      猜你喜欢
      • 2013-04-19
      • 1970-01-01
      • 1970-01-01
      • 2018-04-29
      • 2017-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多