I have a few directives, which will display the same data model in their views. The data will be generated after the ajax call. Currently I put the ajax call into a service, and once the ajax call returned, some variable in the service will be updated. Something like this:
//service
serviceModule.service("myService",function(){
this.data = [];
this.ajaxCall = function(){
...
//in ajax success call back
this.data = response.data;
};
});
//directive A
moduleA.directive("directiveA",function(myService){
return{
templateUrl:'someUrl.html'
link: function(scope){
scope.data = myService.data;
}
}
})
// someUrl.html
<div ng-repeat="line in data">
{{line.abc}}
</div>
My first question is that I am not sure if this is a good approach to update the view based on the ajax return(I mean put the returned data as an attribute in the service, because from the design point of view, it is just a returned value to be assigned somewhere, not some attribute...)
I tried several approaches to automatically detect the change of the service attribute, which leads to a few questions:
1) my original approach(like the pseudo above) does not work, and I wonder why.I thought by using "scope.data=myService.data", myService.data and scope.data are actually pointed to the same memory address, and once the content of that memory address changed, "scope.data" is also changed, and then should be detected by the directive. It will be very helpful if someone can introduce me the mechanism from the memory point of view.
2) Then I did some google search, and found this helpful post: AngularJS : How to watch service variables? then I changed directive a little bit:
//directive A
moduleA.directive("directiveA",function(myService){
return{
templateUrl:'someUrl.html'
link: function(scope){
scope.service = myService;
}
}
})
and in the html, I just use service.data instead of data. It doesn't work until I add $rootScope.$apply() in the service:
serviceModule.service("myService",function(){
this.data = [];
this.ajaxCall = function(){
//in ajax success call back
this.data = response.data;
**$rootScope.$apply();**
};
});
So, Could anyone explain how this $apply,$watch works for in angular?
Thanks a lot!