我有一个 Angular Controller ,它使用工厂从 JSON 文件返回响应。 当我尝试遍历返回的数据时,我在评论中看到以下错误。 但是,如果我在尖括号内使用 HTML 内部的 realArticleData 对象,它会完美地横向移动。我相信这与工厂返回的 promise 有关,但我不确定。
Controller 片段:
function SpecialOrderItemsCtrl($scope, $location, articleDataService) {
$scope.realArticleData = articleDataService.getArticles();
//This throws TypeError: Cannot read property 'thdCustomer' of undefined
$scope.custInfo = $scope.realArticleData.articles.thdCustomer;
}
HTML 片段:
<div ng-controller=SpecialOrderItemsCtrl>
<label>Raw Article JSON</label>
<p>{{realArticleData}}</p>
<label>Json transversed by one level</label>
<p>{{realArticleData.articles}}</p>
<label>THD CUstomer </label>
<p>{{realArticleData.articles.thdCustomer}}</p>
</div>
工厂:
function articleDataService($rootScope, $http) {
articleDataService.data = {};
articleDataService.getArticles = function() {
$http.get('articleData.json')
.success(function(data) {
articleDataService.data.articles = data;
});
return articleDataService.data;
};
return articleDataService;
}
sendDesign.factory('articleDataService', articleDataService);
请您参考如下方法:
您正在处理 promise 。因此,您需要异步处理它们。 如
angular.module('plunker', []).controller('SpecialOrderItemsCtrl', ['$scope', 'articleDataService', function($scope, articleDataService){
// when promise is resolved, set the scope variable
articleDataService.getArticles().then(function(articles){
// store any data from json that you want on the scope for later access in your templates
$scope.articles = articles;
})
}]).factory('articleDataService',['$http', '$q', function($http, $q){
var data = null;
return {
getArticles: function() {
var promise;
if(data === null) {
promise = $http.get('articleData.json').then(function(response){
// cache the response
data = response;
return response;
});
} else {
var deferred = $q.defer();
// promise is immediately resolved with the cached data
// this way both cached and async data can be handled consistently
promise = deferred.promise;
}
return promise;
}
} ;
}]);
Plunkr 链接:http://plnkr.co/edit/7Oas2T