Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - run `$digest` without having `$scope`

I have a controller without $scope

angular.module('todoApp', [])
    .controller('TodoListController', function() {
        var todoList = this;

        todoList.title = "Default title";

        setTimeout(function() {
            todoList.title = "Another title will appear after 5 seconds";
        }, 5000);

        // ...some magic here
    });

And view:

<h1>Current title: {{TodoListController.title}}</h1>

This code won't works correctly, becaufe function in setTimeout won't run $digest() which can update my TodoListController.title.

I know I can use $scope and use $scope.$digest(). But - is it possible to run $digest() without it? I have always access to object angular. Maybe through this object?

like image 271
Kamil P Avatar asked Jan 27 '26 13:01

Kamil P


1 Answers

You should use $timeout instead of vanilla setTimeout.

angular.module('todoApp', [])
.controller('TodoListController', function($timeout) {
    var todoList = this;

    todoList.title = "Default title";

    $timeout(function() {
        todoList.title = "Another title will appear after 5 seconds";
    }, 5000);

    // ...some magic here
});

Using $timeout from angular will handle starting digest cycle.

Angulars $timeout is also useful if you want to notify angular to do updates without delay. In this case you can invoke it without second parameter.

$timeout(function(){
    //something outside angular ...
});

Function passed to $timeout will be invoked on next digest cycle. This way is better than calling $digest manually because it will prevent digest already in progress errors.

like image 76
Krzysztof Atłasik Avatar answered Jan 30 '26 05:01

Krzysztof Atłasik