【问题标题】:ng-repeat filter not applied未应用 ng-repeat 过滤器
【发布时间】:2015-01-08 13:44:52
【问题描述】:

我有一个简单的代码,可以按时间间隔提取一些数据并打印到表格中。我想过滤表格行,但我尝试应用的任何过滤器都会被忽略。我错过了什么?这基本上是来自 AngularJS docs page 的普通副本。

这里唯一的区别似乎是我使用的是控制器而示例代码没有。

例如Plunkr

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>

控制器:

(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();

  }]);

})();

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    过滤器仅适用于您的数据是对象的array。只需将数据转换为数组即可。如果你碰巧使用了lo-dash,这很容易做到:

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

    【讨论】:

    • 我知道这不是最有成效的评论,但是:FACEPALM
    • @SiliconMind - FACEPALM 用于查看 AC w/o VU
    【解决方案2】:

    这是因为你的 ng-repeat 重复的是一个对象而不是一个数组,这里是你的 adminCtrl.rows:

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

    把它变成一个数组:

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

    如果你想对一个对象使用过滤器,你必须自己使用一个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多