【问题标题】:AngularJS $stateful filter with $timeout stuck loopingAngularJS $stateful 过滤器与 $timeout 卡住循环
【发布时间】:2016-03-29 22:17:14
【问题描述】:

我正在尝试使用 AngularJS 创建一个有状态过滤器,以最终调用将异步返回数据的服务。为了测试这一点,我只使用了一个简单的 $timeout 函数,该函数 console.logs 一个字符串。但是,这个 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 触发摘要,过滤器运行每个摘要......这就是无限循环

标签: javascript angularjs angular-filters


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2014-11-21
    • 2020-03-20
    • 2023-04-04
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多