Angularjs:使用ControllerAs时过滤ngRepeat

时间:2015-01-08 13:00:15

标签: angularjs

This post最初问了这个问题,并且包含了一个流行的答案,但我找不到更新代码以使用ControllerAs的方法。

var app = angular.module('myApp', []);

app.filter('slice', function() {
  return function(arr, start, end) {
    return arr.slice(start, end);
  };
});

app.controller('MainController', function() {
  vm = this;
  vm.items = [];
  vm.start = 0;
  vm.end = 20;
  for (var i = 0; i < 100; i++) vm.items.push(i);
  return vm;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller='MainController as main'>
    Start: <input ng-model="main.start"> End: <input ng-model="main.end">
    <ul>
      <li ng-repeat="item in items | slice:main.start:main.end">{{item}}</li>
    </ul>
  </div>
</div>

1 个答案:

答案 0 :(得分:5)

结帐plnkr

使用controllerAs语法时,需要使用控制器指针来访问其属性和方法。

<div ng-app="myApp">
  <div ng-controller='MainController as main'>
    Start: <input ng-model="main.start"> End: <input ng-model="main.end">
    <ul>
      <li ng-repeat="item in main.items | slice:main.start:main.end">{{item}}</li>
    </ul>
  </div>
</div>
</body>