在Angular.js中运行回调之前更改UI

时间:2015-08-09 23:26:24

标签: javascript angularjs

Angular.js应用中,我有这个功能。我希望在调用时,出现加载DIV,然后运行callback()

$scope.startLoading = function (callback) {
    $scope.animation =true; //binded to UI and setting this changes UI
    $scope.errors = false; //binded to UI and setting this changes UI

    callback(); //callback function runs(uploading file) and after that, UI changes!
};

但问题是,在Angular中,在完成该功能后,UI中的任何更改都会受到影响。

现在,我的前两个变量集然后callback()运行,这会完成一项繁重的任务,之后重任务UI更新!但这就是我想要的:当这个函数被调用时,首先变量会发生变化,因为它们会发生UI变化并出现加载DIV,之后回调运行并且重任务开始......我怎么能实现这个?

1 个答案:

答案 0 :(得分:0)

由于未发生$digest周期,因此未对UI进行更改:https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope#$ digest

您可以使用$ timeout来评估下一个摘要周期后的回调,例如:

$scope.startLoading = function (callback) {
    $scope.animation =true; //binded to UI and setting this changes UI
    $scope.errors = false; //binded to UI and setting this changes UI

    // Delay the callback by 10ms
    $timeout(callback, 10); //callback function runs(uploading file) and after that, UI changes!
};

Plunkr:http://plnkr.co/edit/jw2hIAzYRTHCHwaVVAJg?p=preview