Reputation: 241
I want to write time tracker with angular js. I have next HTML code
<tr ng-repeat="task in tasks">
<td>1</td>
<td>{{task.name}}</td>
<td class="text-right">{{task.time}}</td>
</tr>
I have model Task
function Task(name, time) {
this.name = name;
this.time = time;
this.incrementTime = function($scope) {
this.time++;
}
}
So I want to update task every second in controller something like this
function TaskController($scope, $interval) {
$scope.tasks = [];
$scope.addTask = function() {
var task = new Task($scope.task, 0);
$interval( task.incrementTime, 1000 );
$scope.tasks.unshift(task);
$scope.task = '';
}
}
but my table dont update task
Upvotes: 0
Views: 825
Reputation: 27986
Use the $interval service and pass the incrementTime function to the interval
function TaskController($scope, $interval) {
$scope.tasks = []
$scope.addTask = function() {
//add task
var task = new Task($scope.task, 0);
$interval( task.incrementTime, 1000 );
$scope.tasks.push(task);
}
}
and tweak the Task constructor so that that incrementTime references the correct time variable:
function Task(name, time) {
var self = this;
this.name = name;
this.time = time;
this.incrementTime = function() {
self.time++;
}
}
Upvotes: 1
Reputation: 2582
As Gruffy Bunny mentioned, you should use $interval instead of setInterval. $interval is a wrapper for setInterval, but the basic thing that $interval does that setInterval doesn't, is wrapping callback invocation with $scope.apply(yourCallback), which starts a digest cycle that will dirty check your scope models and eventually will update your view.
Upvotes: 0
Reputation: 928
you're setting up var task
as a new Task, not updating the existing one. Something like $scope.task.incrementTime()
is what you want
Upvotes: 0