【发布时间】:2016-01-19 02:05:10
【问题描述】:
// 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:
<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 遍历数组并读取值。
当我第一次加载页面时数组为空,我点击一个链接并返回然后数组和页面被加载。这是为什么呢?
如果我的问题不清楚,请告诉我。非常感谢任何帮助。
【问题讨论】:
标签: javascript jquery arrays angularjs json