Reputation: 3030
I have been playing around with angularjs and calls to rest services to show specific sets of data, however I am struggling with some concepts around custom directives and resources.
At the moment I have a custom directive that loads a list of comments in a system. The list of comments is a custom directive that loads the list through a resource call and shows the list. This is working fine in Page A.
In page B, I show a single user through a url. e.g. site.com/user/3 - this is loaded as a REST resource as the model of the page. This also works fine.
What I am trying to achieve is to put the comments directive in the users page so that it displays a list of comments just by that user. I am working on the assumption that I can somehow take the user and somehow pass it through to the directive as a filter on the comments.
This is approach does not appear to be working. As far as I can tell, the directive is being applied before the promise of the user has been completed, so I end with the unfiltered comments.
In short, how can I get my directive to load the filtered comments after the load of the user data is completed?
Please note I am talking users and comments to give people an idea of what I trying to do. The actual data is more domain-specific, but the data relationships are the same. I also have deliberately not posted the code because I'm trying to understand the correct approach I should be taking, not a specific code issue.
Upvotes: 0
Views: 49
Reputation: 125
I'm not really in favour of hard and fast rules but, in my opinion:
It would look like:
angular.service('CommentService',
function($http, $q){
this.getUserComments = function(userID){
var deferred = $q.defer();
$http.get('site.com/user/' + userID).
success(function(comments) {
deferred.resolve(comments)
}).
error(function(data, status) {
deferred.reject(status);
});
return deferred.promise;
};
}
); // End CommentService
angular.directive('commentList',
function(CommentService){
return {
restrict : 'EA',
template : '<ul><li ng-repeat="comment in comments">{{comment.text}}</li></ul>',
scope : true,
replace : true,
link : function(scope, elem, attrs){
// get User ID from somewhere
var userID = 3;
CommentService.getUserComments(userID).then(
function(comments){
scope.comments = comments;
}
);
}
}
}
);
Hope that makes sense!
Upvotes: 1