I'm sure similar questions have been asked many times on Stack Overflow, but I am still confused.
I have an Angular app that shows a list of articles. The list is long, so it needs to be paginated. For pagination, I'm using UI Bootstrap.
So the app is currently organized like this:
- there is a directive ("home directive") that draws the list of articles
- there is a UI Bootrstrap directive for pagination with its own controller
or, schematically:
Now, when I change the page in the paginator, I need to send the request to the the server, get a new batch of articles and show them in the home directive:
So the paginator's controller is sending the request, but the home directive needs to be aware of the new response and to use it for drawing a new list of articles.
How is this done in Angular? I've read about services/factories, but am not entirely clear how the home directive becomes aware of the new response from the server. Will I need watchers in the home directory, or is this done differently? Could you please explain?
UPDATE:
OK, here is my (failing) attempt to write a service:
home-directive.js
angular.module('myApp')
.directive("homeDirective", [ 'ArticleService', function(ArticleService){
return {
restrict: 'E',
templateUrl: "home.html",
scope: { },
link: function(scope, element, attrs){
ArticleService.getArticles();
scope.$watch('ArticleService.articles', function () {
console.log(ArticleService.articles);
scope.articles = ArticleService.articles;
});
}
}]);
article-service.js
angular.module('myApp')
.service('ArticleService', ['$http', function($http){
var that = this;
this.getArticles = function(){
$http.get('/path/to/api').success(function(data) {
console.log('working');
that.articles = data;
console.log(that.articles);
});
};
}]);
The call to ArticleService.getArticles()
from the directive starts the getArticles()
function, as I can see from the logger in the console. The server sends its response. that.articles
changes. However, the directive fails to register the change of ArticleService.articles
and doesn't get the data.
UPDATE 2
OK, if in the directive, before setting a watcher, I add this line in the directive:
scope.ArticleService = ArticleService;
then it will work.