[英]Angular - run `$digest` without having `$scope`
我有一個沒有$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
});
並查看:
<h1>Current title: {{TodoListController.title}}</h1>
這段代碼無法正常工作,因為setTimeout
函數不會運行$digest()
,它可以更新我的TodoListController.title
。
我知道我可以使用$scope
並使用$scope.$digest()
。 但是 - 沒有它可以運行$digest()
嗎? 我總是訪問對象angular
。 也許通過這個對象?
你應該使用$timeout
而不是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
});
使用$timeout
from angular將處理開始摘要周期。
如果要通知angular進行更新而不延遲,Angulars $ timeout也很有用。 在這種情況下,您無需第二個參數即可調用它。
$timeout(function(){
//something outside angular ...
});
傳遞給$timeout
函數將在下一個摘要周期調用。 這種方式比手動調用$ digest更好,因為它會阻止digest already in progress
錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.