Monday, June 24, 2013

Manipulating server data in an Angular controller

I was experiencing an annoying problem every time I was trying to access data I would get back from the server in an Angular.JS controller.
 
As it turns out, every time I shorthanded and wrote something in the essence of:
$scope.myData = Service.getMyData();
It returns a proxy object that the angular view was able to handle though model binding,  but the controller can't and accessing fields of the returned object would return as undefined.

So, the solution is as simple as it it stupid (Also see angular reference):
By passing a function to the service that would catch the returning data, and do the magic there, the returning object is the data itself and not a proxy.
the shorthand should be replaced with:
Service.getMyData({}, function(d){
      $scope.myData= d;
});

In my implementation I often broadcast an event of my own after the data has returned so other controllers that are dependent on this data my react accordingly:

Service.getMyData({}, function(d){
      $scope.myData= d; 
      Context.broadcast("theDataIsReady");//shaking the $rootScope tree
}); 
 
...
 
$scope.$on("theDataIsReady",function(){
     
// a very clever snippet of code
  }); 

Special thanks to Ravit.

No comments:

Post a Comment

Please do not post spam on this blog, Spam sites will be reported to google.
thank you kindly.