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.

Saturday, June 8, 2013

Angular.js JSONP with Rails

A couple of snippets to remind myself on how to JSONP angular and rails. (cross domain Ajaxing)



- -

Wednesday, June 5, 2013

App Context for Angular.JS

I'm now deep into converting the Wikibrains client application to the Angular.js Javascript infrastructure.
One of the most basic tools I needed was an application wide context to shift around data and events between controllers.

This is what I came up with: