0
// SETTING UP SERVICES
app.service("PictureService", function($http) {
var Service = {};
Service.pictureLinkList = [];
// GETTING PICTURE LINKS FOR PAGE
$http.get("data/img_location.json")
.success(function(data) {
Service.pictureLinkList = data;
})
.error(function(data,status) {
alert("Things went wront!");
});
Service.findImgById = function(id) {
for(var item in Service.pictureLinkList) {
if(parseInt(Service.pictureLinkList[item].id) === parseInt(id)) {
return Service.pictureLinkList[item];
}
}
}
return Service;
});
// COMMENT SERVICE START*****************************************
app.service("CommentService", function($http) {
var comService = {};
comService.commentList = [];
// GETTING COMMENTS FROM JSON FILE
$http.get("data/comments.json")
.success(function(response){
comService.commentList = response;
for(var item in comService.commentList){
comService.commentList[item].date = new Date(comService.commentList[item].date).toString();
}
})
.error(function(data,status){
alert("Things went wrong!");
});
comService.findCommentById = function(id) {
var comArr = [];
for(var item in comService.commentList) {
if(parseInt(comService.commentList[item].imgId) === parseInt(id)) {
comArr.push(comService.commentList[item]);
}
}
return comArr;
};
return comService;
});
// Controller
app.controller("pictureDetails", ["$scope", "PictureService", "CommentService", "$routeParams", function($scope, PictureService, CommentService, $routeParams) {
$scope.imgById = PictureService.findImgById($routeParams.id);
$scope.commentsById = CommentService.findCommentById($routeParams.id);
}]);
下面是HTML:當你第一次點擊鏈接Angularjs時,數組不會加載?
<ul>
<li ng-repeat="item in commentsById">
<div class="panel panel-primary text-center"><h3>Posted by: {{ item.postedBy }} at </h3><p>{{ item.date }}</p></div>
<div class="panel-body text-center">{{ item.comment }}</div>
</li>
Comments.json文件:
[
{"id": 1, "imgId": 1, "comment": "Pretty good sketching there pal!", "date": "October 1, 2014 11:13:00", "postedBy": "John"},
{"id": 2, "imgId": 1, "comment": "Nice one keep working on your skills", "date": "January 17, 2016 11:48:00", "postedBy": "John"}
]
首先,我一直在使用Angularjs剛開始真的很喜歡它的框架。問題是當我加載html頁面$ http服務讀取json文件並返回分配給數組的對象。然後,我使用ng-repeat來遍歷數組並讀取值。
當我第一次加載頁面數組是空的,我點擊一個鏈接,然後返回數組和頁面被加載。這是爲什麼?
如果我不清楚我的問題,請讓我知道。任何幫助是極大的讚賞。