我有一个对话框 Controller :
.controller('loadingDialogCtrl', function($scope, $mdDialog, $rootScope, loadingDialog) {
$scope.loadingDialog = loadingDialog;
});
在我的另一个 Controller 中,我显示此对话框 Controller 并通过 LoadingDialogService
对其进行操作:
.controller('myCtr', function($scope, $mdDialog, loadingDialog) {
$mdDialog.show({
controller: 'loadingDialogCtrl',
templateUrl: 'tmpl/loadingDialog.tmpl.html'
});
loadingDialog.status = "Formatting...";
})
LoadingDialog
服务:
angular.module('LoadingDialogService', []).service('loadingDialog', function ($mdDialog) {
this.progress = 0;
this.status = "Loading data from board...";
this.additionalStatus = "";
this.mode = "determinate";
return {
progress: this.progress,
status: this.status,
additionalStatus: this.additionalStatus,
mode: this.mode
}
});
这很好用。但例如,如果我更改异步函数中的服务值,我的对话框 View 不会更新:
//progress bar inside dialog have changed
loadingDialog.progress = 55;
setTimeout(function () {
//progress bar inside dialog didn't change
loadingDialog.progress = 55;
}, 10)
最佳答案
在loadingDialogCtrl
中代替
$scope.loadingDialog = loadingDialog;
你应该使用
$rootScope.$watch(function() {
return loadingDialog;
}, function(loadingDialogValue) {
$scope.loadingDialog = loadingDialogValue;
}, true);
OR(更优雅的解决方案)
$scope.getLoadingDialog = function() {
return loadingDialog;
};
关于javascript - 服务异步更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41957489/