Angular limitTo不返回正确的输出

时间:2016-05-12 09:31:42

标签: javascript angularjs angularjs-ng-repeat

我想以下代码的输出应该是 text 3 text 4 ,但是没有得到正确的输出。那里的代码有问题吗?

HTML

<body ng-app="angularjs-starter" ng-controller="MainCtrl">
    <h1>Hello {{name}}</h1>
    <div ng-repeat="t in getTimes(4) | limitTo:-2">text {{$index+1}}</div>
  </body>

JS

var app = angular.module('angularjs-starter', []);

  app.controller('MainCtrl', function($scope) {
     $scope.name = 'World';
     $scope.getTimes = function(n) {
       return new Array(n);
     };
});

2 个答案:

答案 0 :(得分:2)

无论您的$index过滤器是什么,

limitTo始终都会从0开始。所以只需在绑定表达式中直接使用t

  <body ng-app="angularjs-starter" ng-controller="MainCtrl">
    <h1>Hello {{name}}</h1>
    <div ng-repeat="t in getTimes(4) | limitTo:-2">text {{t}} </div>
  </body>

  var app = angular.module('angularjs-starter', []);

  app.controller('MainCtrl', function($scope) {
    $scope.name = 'World';
     $scope.getTimes=function(n){
       return new Array(n);
     };
});

答案 1 :(得分:1)

您的代码无效,因为您的论集中有重复项,而getTimes()正在重新调整[undefined, undefined, undefined, undefined]

在这种情况下,使用t in getTimes(4) | limitTo:-2 track by $index进行正确的数组初始化或使用避免重复的函数。

另一个问题是$index始终以 0 开头。因此,您不会像预期的那样获得 text 3 text 4 。如果需要数组值,则需要使用text {{t}}

示例:

按$ index跟踪

&#13;
&#13;
var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {
    $scope.name = 'World';
    $scope.getTimes=function(n){
        return new Array(n);
    };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="angularjs-starter" ng-controller="MainCtrl">
    <h1>Hello {{name}}</h1>
    <div ng-repeat="t in getTimes(4) | limitTo:-2 track by $index">text {{$index+3}}</div>
</body>
&#13;
&#13;
&#13;

顺序数组

&#13;
&#13;
var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {
    $scope.name = 'World';
    $scope.getTimes = function(n){
        return Array.apply(null, {length: n}).map(Number.call, Number); // [0, 1, ..., n-1]
    };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="angularjs-starter" ng-controller="MainCtrl">
    <h1>Hello {{name}}</h1>
    <div ng-repeat="t in getTimes(4) | limitTo: -2">text {{t+1}}</div>
</body>
&#13;
&#13;
&#13;