如何将$ q.all promise中的对象绑定到AngularJS中的$ scope?

时间:2015-12-24 10:05:08

标签: angularjs angularjs-scope angular-promise

在我的应用程序中,我有一个服务创建一个带有两个json文件的新结构。所以,我使用$ q.all在同一时间使用它们。

    angular.module('myApp', []).factory('myService', ['$http', '$q', function ($http, $q) {

var myStructure = function () {
    var firstJson = $http.get('datas/firstJson.json');
    var secondJson = $http.get('datas/secondJson.json');

    return $q.all([firstJson, secondJson]).then(function (values) {
        var myMap = new Map();
        /*
        treatment on myMap
        */

        return myMap.values();
    });
}

return myStructure();
}]);

因此,我使用myService.then

在myController中使用此服务
var myApp = angular.module('myApp');
myApp.controller('myApp', ['$scope', 'myService', function ($scope, myService) {
myService.myStructure.then(function(value){
    $scope.myStructure = value;
    });}]);

最后,当我在HTML页面中使用{{myStructure}}时,在使用ng-controller实例化myApp之后,页面显示{}(一个空对象)。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

将myMap逻辑移动到控制器中的resolve callback中

服务:

angular.module('myApp', []).factory('myService', ['$http', '$q',    function ($http, $q) {

        var myStructure = function () {
            var firstJson = $http.get('datas/firstJson.json');
            var secondJson = $http.get('datas/secondJson.json');

            return $q.all([firstJson, secondJson]);
        }

        return myStructure();
    }]);

控制器:

var myApp = angular.module('myApp');
    myApp.controller('myApp', ['$scope', 'myService', function ($scope, myService) {
        myService.myStructure.then(function(values){
          var myMap = new Map();
          /*
          treatment on myMap
          */               
          $scope.myStructure = myMap.values();
        });
      }]);