【问题标题】:ng-repeat limitTo automaticly trims limit and doesn't return it backng-repeat limitTo 自动修剪限制并且不返回它
【发布时间】:2016-07-15 09:48:51
【问题描述】:

我有在应用程序中更改的项目数组。 当我删除项目时,limitTo 会自动修剪其限制值,但是当我添加项目时,它不会返回原始限制值。就像 limit=5 和 items.length 变为 2 limitTo 值变为 3 并且当 items.length 增加时永远不会增长回 5。升级限制不起作用。

JS:
    $scope.filterLimit = 5;
    $scope.itemList2 = ['item1', 'item2', 'item3', 'item4']

HTML:

<div ng-repeat="i in itemList2 | limitTo: filterLimit">
  <h5>{{i}}</h5>
</div>
<button ng-click="itemList2.push('new item')"> Add </button><br>
<button ng-click="itemList2.length = itemList2.length-1"> Delete </button><br>
<button ng-click="filterLimit = filterLimit+1"> Update </button>

【问题讨论】:

  • 请检查我的答案。

标签: angularjs angularjs-ng-repeat ng-repeat


【解决方案1】:

嗯,主要问题是您将相同的元素添加到列表中,所以ngRepeat 声称它给出了以下错误:ngRepeat:dupes

要解决它,你必须在你的ngRepeat 中使用track by 表达式,像这样:

<div ng-repeat="i in itemList2 | limitTo: filterLimit track by $index">

注意:过滤器,如limitToorderBy 等...必须位于track by 表达式之前。

另外,我建议您使用 controller 中的 functions 来代替 ng-click(),而不是全部查看。

这是一个修复了所有问题的版本:

angular.module('app', [])
  .controller('mainCtrl', function($scope) {
    $scope.filterLimit = 5;
    $scope.itemList2 = ['item1', 'item2', 'item3', 'item4'];

    $scope.add = function() {
      $scope.itemList2.push('item');
    }

    $scope.delete = function() {
      $scope.itemList2.pop();
    }

    $scope.increment_filter = function() {
      $scope.filterLimit++;
    }
  });
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  <div ng-repeat="i in itemList2 | limitTo: filterLimit">
    <h5 ng-bind="i"></h5>
  </div>
  <button ng-click="add()"> Add </button>
  <br>
  <button ng-click="delete()"> Delete </button>
  <br>
  <button ng-click="increment_filter()"> Update </button>

  <hr> 
  List: <pre ng-bind="itemList2"></pre>
  Limit: <pre ng-bind="filterLimit"></pre>
</body>

</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    相关资源
    最近更新 更多