0

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

3 Answers 3

1

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++;
    }
}

Fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

It's still not working for me plnkr.co/edit/?p=streamer&s=GYw5zvmCIPpQoxHC
The fiddle works - the plunker incrementTime is using the wrong 'this'
0

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.

1 Comment

1. You don't need form and ng-submit, just use ng-click. 2. you're using an old version of angular which didn't have $interval, use the recent version.
0

you're setting up var task as a new Task, not updating the existing one. Something like $scope.task.incrementTime() is what you want

3 Comments

But I have model Task function Task(name, time) { ... }
You're creating a new Task object and altering that, not altering the $scope.task like you're wanting to. If you want to use new Task you need to add this new task object to $scope.tasks
Yes I added $scope.tasks.unshift(task), but table still not updated, if I changed time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.