0

I've been able to use the following to get my jSON which is fine but I've been told that using a Factory and Service would be a better option. For the life of me I'm unable to get anything working and I can't even see why I should use a Factory.

Could someone advise why or at least help me out at all? My main requirement here is to get the jSON and then pass it through into an <li></li> list for each object (I haven't tried to get this working yet).

theApp.controller('MenuSideController', ['$scope','$http', function ($scope, $http){
    $http.get('/directory/assets/inc/category.php').success(function(data) {
        $scope.list = data;
    });

}]);

1 Answer 1

1

What if you wanted to make the same server call in another controller. Would you copy&paste the same $http.get(... code? No, of course not, because that would be a really bad code smell and a prime example of DRY (Don't Repeat Yourself) violation.

This is why your $http needs to go into a separate function (call it "service" or "factory"), which you will be able to call from anywhere.

theApp.controller('MenuSideController', [
  '$scope',
  'CategoryService',
  function ($scope, CategoryService){
    CategoryService.getList()
      .success(function(list){
        $scope.list = list;
      });

  }
]);

theApp.factory('CategoryService', [
  '$http',
  function($http){
    return {
      getList: function(){
        return $http.get('/directory/assets/inc/category.php');
      }
    };
  }

]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.