2016-12-04 56 views
-3

我想從控制器「menuBarCtrl」調用Angular服務函數「getDecks()」。我想在getDecks()返回我的JSON文件的內容後,將文件內容存儲在本地$ scope變量中。通過角度服務加載JSON文件

但是,如果我嘗試在控制檯中顯示該值,我只會得到'未定義'。

ajapp.controller('MenuBarCtrl', function($scope, $http, CardProvider) { 

    $scope.decks = CardProvider.getDecks(); 

    console.log($scope.decks); 

}); 

ajapp.service('CardProvider', function($http) { 

    this.getDecks = function(){ 

     var json; 
     $http.get('content/SetList.json').success(function(data, status){ 

      json = data; 
     }).error(function (data, status) { 
      alert("File Request Failed ["+status+"]"); 
     }); 

     return json; 
    } 
}); 
+0

試''回報聲明。 –

+3

你知道承諾是如何工作的嗎? –

回答

0

該問題的角度不是JS的異步性。

這似乎是你想要什麼來實現的:在`$ http.get`函數內部

ajapp.controller('MenuBarCtrl', function($scope, $http, CardProvider) { 
    CardProvider.getDecks() 
    .then(function(data) { 
     $scope.decks = data; 
    }) 
    .catch(function (data, status) { 
     /* handle error*/ 
    }); 
}); 

ajapp.service('CardProvider', function($http) { 
    this.getDecks = function(){ 
     return $http.get('content/SetList.json'); 
    } 
});