【发布时间】:2015-03-12 13:52:02
【问题描述】:
我有一个数组,其中包含我发送给外部应用程序的许多命令。
$scope.commandLog = [{"id":"1", "time":"12.02.2015 20:05:20.606","command":"cmd1", "status":"idle"},
{"id":"2", "time":"12.02.2015 20:05:20.606","command":"cmd2", "status":"idle"},
{"id":"3", "time":"12.02.2015 20:05:20.606","command":"cmd3", "status":"idle"},
{"id":"4", "time":"12.02.2015 20:05:44.162","command":"cmd4", "status":"idle"},
{"id":"5", "time":"12.02.2015 20:05:44.162","command":"cmd5", "status":"success"},
{"id":"6", "time":"12.02.2015 20:05:44.162","command":"cmd6", "status":"idle"},
{"id":"7", "time":"13.02.2015 12:05:52.181","command":"cmd7", "status":"idle"},
{"id":"8", "time":"13.02.2015 12:05:52.181","command":"cmd8", "status":"idle"}]
我正在循环数组,并在下一个循环开始之前设置一个延迟。这工作正常。
for (var i = 0; i < $scope.commandLog.length; i++)
{
(function(index) {
setTimeout(function() {
// DO STUFF HERE
}, i * 2000);
})(i);
}
我想改变当前数组索引处对象的状态,如下所示:
$scope.commandLog[index].status = 'active';
我有一个显示命令及其状态的表格
<table class="table table-hover">
<thead>
<th>Time</th>
<th> </th>
<th>Command</th>
<th>Status</th>
</thead>
<tbody>
<tr ng-repeat="cmd in commandLog" ng-class="cmd.status" ng-attr-id="{{ 'command-' + cmd.id }}">
<td>{{cmd.time}}</td>
<td> <span class="btn btn-primary" ng-click="sendCommand(cmd.command)"><i class="fa fa-play"></i></span></td>
<td>{{cmd.command}}</td>
<td>{{cmd.status}}</td>
</tr>
</tbody>
</table>
问题是单元格<td>{{cmd.status}}</td> 没有更新为“活动”,即使当我将对象写入控制台时,我确实看到状态设置为活动。
如果我没有延迟地运行代码,只需 for 循环,它就可以工作。
完整代码的JSFiddle:https://jsfiddle.net/8ezh6Ljh/1/
如果有人能解释我做错了什么,我将不胜感激。 TIA
【问题讨论】:
-
使用
$timeout服务而不是传统的setTimeout。 -
如果您更改集合中的对象,您需要使用 Watch:docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch 或 WatchCollection: docs.angularjs.org/api/ng/type/… 取决于您的需要。
标签: javascript angularjs settimeout