在控制器中侦听2个或更多值

时间:2014-11-10 16:11:25

标签: angularjs

我的控制器加载时,我有一个$scope.loadingtrue

当我收到来自多个来源的所有数据时,我想将其设置为false

app.controller('MyController', function ($scope, dataFactory) {

$scope.loading = true;
$scope.gotData1 = false;
$scope.gotData2 = false;
$scope.gotData3 = false;



//Get Data 1
    dataFactory.getData1().then(function (response) {
        //...
        $scope.gotData1 = true;
    }, function (error) {
        //...
    });

//Get Data 2
    dataFactory.getData2().then(function (response) {
        //...
        $scope.gotData2 = true;
    }, function (error) {
        //...
    });

//Get Data 3
    dataFactory.getData3().then(function (response) {
        //...
        $scope.gotData3 = true;
    }, function (error) {
        //...
    });

});

1 个答案:

答案 0 :(得分:6)

使用$q.all

$scope.loading = true;

//Get Data 1
var promise1 = dataFactory.getData1();
promise1.then(function (response) {
    //...
    $scope.gotData1 = true;
}, function (error) {
    //...
});

//Get Data 2
var promise2 = dataFactory.getData2();
promise2.then(function (response) {
    //...
    $scope.gotData2 = true;
}, function (error) {
    //...
});

//Get Data 3
var promise3 = dataFactory.getData3();
promise3.then(function (response) {
    //...
    $scope.gotData3 = true;
}, function (error) {
    //...
});

$q.all([promise1, promise2, promise3]).then(function(){
    $scope.loading = false;
});