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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With