Kamil P
Kamil P

Reputation: 784

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?

Upvotes: 3

Views: 623

Answers (2)

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22635

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.

Upvotes: 2

Danilo Velasquez
Danilo Velasquez

Reputation: 501

You must use the angular version of timeout: $timeout.

https://docs.angularjs.org/api/ng/service/$timeout

This service trigger the angular $digest process.

Upvotes: 0

Related Questions