I have an array that will contain many commands that I send to an external application.
$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"}]
I am looping over the array, and set a delay before the next loop begins. This is working fine.
for (var i = 0; i < $scope.commandLog.length; i++)
{
(function(index) {
setTimeout(function() {
// DO STUFF HERE
}, i * 2000);
})(i);
}
I want to change the status of the object at the current array index like so:
$scope.commandLog[index].status = 'active';
I have a table that shows the commands and their status
<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>
The problem is that the cell <td>{{cmd.status}}</td>
is not updating to "active" even though when I write the object to the console, I do see that the status is set to active.
If I run the code without the delay, just the for loop, it does work.
JSFiddle with the complete code: https://jsfiddle.net/8ezh6Ljh/1/
I would really appreciate it if someone could explain what I am doing wrong. TIA
Your code inside the setTimeout
function is running outside of angular world.
To let angular know about changes you made to your data, either call $scope.$apply()
or use the $timeout
service.
Check this plunker
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments