Where to Manipulate Data Gotten via AJAX Service? Link fn or Controller?

Viewed 236

I have a HTML partial that I'm trying to bind AJAX data too. For some reason, it seems I must put the AJAX service call within the directive's link function. I cannot just put it in the controller; I do it in the directive like this:

link: function(scope){
  MyService.getData().then(function(res){
    scope.myData = res.data;
  }, function(res){
    throw new Error('Error getting data');
  });
}

First of all, I'm curious why I cannot do this in my controller. But also, There is some manipulation I want to do to the data once I get it. Does that all need to happen in the linked function. In the controller looping over $scope.myData won't work because it isn't defined yet? Can I use my AJAX data in my controller somehow without having to do my logic in a linked file?

5 Answers
Related