所以我有一个从服务器获取对象的工厂:
.factory('Articles', function($http) {
var articles = [];
return {
all: function(){
$http.get("http://jsonp.afeld.me/?url=http://examplesite.com/page.html?format=json").then(function(response){
articles = response.data.items;
console.log(response.data.items);
return articles;
});
},
get: function(articleId) {
for (var i = 0; i < articles.length; i++) {
if (articles[i].id === parseInt(articleId)) {
return articles[i];
}
}
return null;
}
}
});
这样会返回一个数组:
[Object, Object, Object, Object, Object, Object, Object, Object]
每个对象看起来像这样:
0: Object
alias: "title"
attachments: Array[0]
author: Object
category: Object
catid: "67"
created: "2015-04-11 08:06:07"
created_by_alias: ""
events: Object
extra_fields: null
featured: "0"
fulltext: ""
gallery: null
hits: "80"
id: "171"
image: ""
imageLarge: "/url/69bc9c3e85c501b0a6208cc7a55abbf9_L.jpg"
imageMedium: "/url/69bc9c3e85c501b0a6208cc7a55abbf9_M.jpg"
imageSmall: "/url/69bc9c3e85c501b0a6208cc7a55abbf9_S.jpg"
imageWidth: ""
imageXLarge: "/url/69bc9c3e85c501b0a6208cc7a55abbf9_XL.jpg"
imageXSmall: "/url/69bc9c3e85c501b0a6208cc7a55abbf9_XS.jpg"
image_caption: ""
image_credits: ""
introtext: "<p><strong>Mpho Mathoho</strong>lots of text is here....</p>"
language: "*"
link: "/url/title.html"
modified: "2015-06-02 07:44:30"
numOfComments: "0"
numOfvotes: "(0 votes)"
tags: Array[1]
title: "the title"
video: null
video_caption: ""
video_credits: ""
votingPercentage: 0
__proto__: Object
我的控制器看起来像这样:
.controller('GautengCtrl', function($scope, $stateParams, Articles) {
$scope.articles = Articles.all();
})
我想做的就是返回文章列表并在页面上显示。我的HTML看起来像这样:
<ion-list>
<ion-item ng-class='{in:$first}' class="item-remove-animate item-thumbnail-left item-icon-right wrap" ng-repeat="article in articles" type="item-text-wrap" href="#/app/provinces/gauteng/{{article.id}}">
<img ng-src="http://examplesite.com/{{article.imageLarge}}">
<h2>{{article.title}}</h2>
<p>{{article.created}}</p>
<i class="icon ion-chevron-right icon-accessory"></i>
</ion-item>
</ion-list>
这不起作用,我真的不明白为什么。
有没有人对此有任何见解可以提供帮助?
答案 0 :(得分:2)
我认为您的问题可能与承诺有关。请记住,当您使用$ http时,您将创建承诺,并且在使用返回数据时应使用相应的回调。
在您已使用.then方法的服务中,但您实际上并未将任何内容从服务返回到控制器。您应该返回生成的promise并使用.then / .error方法更新$ scope变量。
.factory('Articles', function ($http) {
var articles = [];
return {
all: function () {
return $http.get("http://jsonp.afeld.me/?url=http://examplesite.com/page.html?format=json").then(function (response) {
articles = response.data.items;
console.log(response.data.items);
return articles;
});
},
get: function (articleId) {
for (var i = 0; i < articles.length; i++) {
if (articles[i].id === parseInt(articleId)) {
return articles[i];
}
}
return null;
}
}
});
在您的控制器中
.controller('GautengCtrl', function ($scope, $stateParams, Articles) {
$scope.articles = [];
Articles.all().then(function(data){
$scope.articles = data;
});
})