AngularJS$带$timeout的有状态过滤器陷入循环

AngularJS $stateful filter with $timeout stuck looping

本文关键字:过滤器 循环 状态 timeout AngularJS      更新时间:2023-09-26

我正试图用AngularJS创建一个有状态过滤器,以最终调用一个异步返回数据的服务。为了测试这一点,我只使用了一个简单的$timeout函数来console.log一个字符串。然而,这个console.log只是无限地运行。

export default angular.module('components.filters.combine-name', [])
.filter('combineName', ['$timeout', function ($timeout) {
  function combineName(input) {
    $timeout(function () {
      console.log('test');
    }, 1000);
    return input.firstName + ' ' + input.lastName;
  }
  combineName.$stateful = true;
  return combineName;
}]);

html

<table class="table table-bordered table-striped table-responsive">
    <thead>
    <tr>
      <th>
        <div class="th">
          Name
        </div>
      </th>
      <th>
        <div class="th">
          Status
        </div>
      </th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="result in vm.results">
      <td>{{result | combineName}}</td>
      <td>{{result.status}}</td>
    </tr>
    </tbody>
</table>

控制器:

this.results = [
  {
    firstName: 'Johnny',
    lastName: 'Utah',
    status: 'Active'
  },
  {
    firstName: 'Richard',
    lastName: 'Reynolds',
    status: 'Inactive'
  },
  {
    firstName: 'Randy',
    lastName: 'Johnson',
    status: 'Active'
  }
];

使用$timeout,您基本上打开循环,它会一直这样做,除非您告诉它停止。

在循环中使用:$timeout.cancel();