The task can be done in various ways but the question is that which practice is the best.
First of all if you have a directive with partial and you want to bind to it, you can do it in the directive's controller
app.directive('myPartial', function() {
return {
restrict:'AE',
template:'<pre>[{{myData| json}}]</pre>',
scope:true,
link:function(scope, elem, attrs) {
/*avoid using model manipulation in link function as it is mostly used
for DOM manipulation such as angular.element(elem).addClass('myTemplateClass');*/
},
controller: function($scope,MyService){
MyService.getData().then(function(dataFromServer){
scope.myData = dataFromServer;
}, function(err){
throw new Error('Error getting data : ' + err);
});
}
};
});
You have to have THIN controllers and THICK services when working with AngularJS.. if you have to manipulate data. Do it in the service and return such form of data to controller which is directly assignable to the controller. That's the best practice. I.e. in your service. Do this
app.factory('MyService',function($http,$q){
var _modifyGetData = function(serverData){
// modify your data here...
// for example -> serverData.usersCount = serverData.users.length;
return serverData;
};
var getData = function(){
var dfd = $q.defer();
$http.get(/*Some url here*/).then(function(res){
var data = res.data;
// manipulate all your data using a function maybe
data = _modifyGetData(data);
dfd.resolve(data); //resolve the modified data
});
return dfd.promise;
}
return {
getData:getData
};
});
Hope this helps.
Some of the online sources that might help:
https://scotch.io/tutorials/making-skinny-angularjs-controllers
https://teamgaslight.com/blog/4-lessons-learned-doing-angular-on-rails