簡體   English   中英

Angular - 運行`$ digest`而沒有`$ scope`

[英]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錯誤。

您必須使用超時的角度版本:$ timeout。

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

此服務觸發角度$摘要過程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM