11

Let's say on click of a button(in the view), the requirement is: to fetch the data from the server. I am confused whether or not the business logic to

i) fetch the data and

ii) validation of it should be done inside the controller or inside the factory(or service)

Should it be placed in the factory or in the controller? Please help!!

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
ashok_khuman
  • 599
  • 2
  • 8
  • 17

2 Answers2

14

The purpose of controllers is binding data to your view. They should not contain any logic and merely communicate with your services.

homeModule.controller('homeCtrl',function($scope,Categories){
  $scope.categories = Categories.items;
});

Add a function to your service that fetches the data and stores it on itself:

fetchAll: function(){

  var defer = $q.defer();
  var self = this;

  $http.get(URL})
    .then(function(res){
        self.data = res.data;
        defer.resolve();
    });

  return defer.promise;
},

(Note that this is just one possible way to do things. Nothing prevents you from returning the data instead of storing it on the service. Do as you need.)

If possible, you should consider fetching your data before your view gets initialized. By doing so, you can ensure that necessary data is available as soon as the user get's the page.

See $http request before AngularJS app initialises?

Further reading

https://docs.angularjs.org/guide/services (Read the complete developer guide)

http://toddmotto.com/rethinking-angular-js-controllers/

Also I recommend the official Tutorial

Community
  • 1
  • 1
Wottensprels
  • 3,307
  • 2
  • 29
  • 38
2

You should place the business logic in the service. Controllers should just take data from services and bind it to the UI.

If you want to learn more about best practices in angular I recommend this video on pluralsight.com:

http://pluralsight.com/training/courses/TableOfContents?courseName=angular-best-practices&highlight=

Liviu Mandras
  • 6,540
  • 2
  • 41
  • 65