ngplayground
ngplayground

Reputation: 21627

AngularJS using get to get json properly

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;
    });

}]);

Upvotes: 0

Views: 42

Answers (1)

Stewie
Stewie

Reputation: 60416

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');
      }
    };
  }

]);

Upvotes: 1

Related Questions