简体   繁体   English

ng-repeat过滤器未应用

[英]ng-repeat filter not applied

I have a simple code that pulls some data in intervals and prints into a table. 我有一个简单的代码,可以按间隔提取一些数据并将其打印到表中。 I'd like to filter the table rows but any filters that I'm trying to apply are ignored. 我想过滤表行,但是我尝试应用的所有过滤器都会被忽略。 What am I missing? 我想念什么? This is basically a plain copy from AngularJS docs page . 这基本上是AngularJS 文档页面的纯副本。

The only difference here seems to be that I'm using a controller and the example code does not. 这里唯一的区别似乎是我使用的是控制器,而示例代码并未使用。

Example Plunkr . 示例Plunkr

HTML template: HTML模板:

<table>
  <thead>
    <tr>
      <th>Pages</th>
      <th>Last action</th>
      <th>Total time</th>
    </tr>
    <tr>
      <th><input ng-model="search.count"></th>
      <th><input ng-model="search.last"></th>
      <th><input ng-model="search.time"></th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="row in adminCtrl.rows | filter:search ">
      <td>{{ row.count }}</td>
      <td>{{ row.last }}</td>
      <td>{{ row.time }}</td>
    </tr>
  </tbody>
</table>

Controller: 控制器:

(function(){
  var app = angular.module('admin', []);

  app.controller('AdminController', ['$interval', '$http', function($interval, $http){
    var admin = this;
    admin.rows = [];
    var timer = undefined;

    function updateRows() {
      $http.get('test.json').success(function(data) {
        admin.rows = data;
      });
    }

    admin.stopTimer = function() {
      if (angular.isDefined(timer)) {
        $interval.cancel(timer);
        timer = undefined;
      }
    };

    admin.startTimer = function(delay) {
      if (!angular.isDefined(delay)) {
        // Default interval 10 seconds.
        delay = 10000;
      }

      if (!angular.isDefined(timer)) {
        timer = $interval(updateRows, delay);
      }
    };

    admin.isTimerRunning = function() {
      return angular.isDefined(timer);
    }

    // Initialize rows.
    updateRows();

    // Start the interval timer.
    admin.startTimer();

  }]);

})();

It's because your ng-repeat is repeating over an object and not an array, here is your adminCtrl.rows: 这是因为您的ng-repeat是在对象而非数组上重复,这是您的adminCtrl.rows:

{"a":{"count":14,"last":"Lorem ipsum","time":45},"b":{"count":5,"last":"Some title","time":13}}

Make it an array: 使其成为数组:

[{"count":14,"last":"Lorem ipsum","time":45},{"count":5,"last":"Some title","time":13}}]

If you want to use filter over an object, you'll have to roll your own using a 如果要对对象使用过滤器,则必须使用

.filter("MY_FILTER", function(){
    ...
});

the filter is only apply in array where your data is an object. 过滤器仅适用于数据为对象的array simply convert the data to array should work. 只需将数据转换为数组即可。 if you happend to use lo-dash , that's a easy job to do : 如果您碰巧使用lo-dash ,那就很容易做到:

function updateRows() {
    $http.get('test.json').success(function(data) {
        admin.rows = _.toArray(data);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM