// 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来遍历数组并读取值。
当我第一次加载页面数组为空时,我点击链接然后返回数组并加载页面。那是为什么?
如果我不清楚我的问题,请告诉我。非常感谢任何帮助。
答案 0 :(得分:0)
$scope.$watch( function(){ return CommentService.commentList; }, function(comments) {
for(var item in comments) {
if(parseInt(comments[item].imgId) === parseInt($routeParams.id)) {
$scope.commentsById.push(comments[item]);
}
}
console.log($scope.commentsById);
});
$scope.commentsById = [];
将这篇文章添加到控制器工作中,正在读一本关于Angularjs的书,他们解释它就像$ watch变量监视任何给定的数组并将其分配给任何东西。
如果需要更多解释请告诉我。它现在完美地工作,我点击它一次,并加载评论。一次加载整个注释数组。