Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I move HTTP requests out of an AngularJS controller and into a service?

Tags:

angularjs

I have the following code snippet:

    angular.module('test', []).controller('TestCtrl', function ($scope, $http) {
        $scope.selectedTestAccount = null;
        $scope.testAccounts = [];

        $http({
            method: 'GET',
            url: '/Admin/GetTestAccounts',
            params: { applicationId: 3 }
        }).success(function (result) {
            $scope.testAccounts = result;
        });
    }

It was suggested to me that I should maybe consider creating service(s) for $http requests Can someone give me an example of how I could do this for the code above. In particular I am not sure how to set up the service and make the controller inject it.

like image 382
Alan2 Avatar asked Mar 31 '13 07:03

Alan2


1 Answers

Your service needs to look something like this:

angular.module('testaccount', []).
factory('TestAccount', function($http) {
  var TestAccount = {};
  TestAccount.get = function(applicationId, callback) {
    $http.get('/Admin/GetTestAccounts?applicationId=' + applicationId).success(function(data) {
      callback(data);
    });
  };
  return TestAccount;
});

Your controller needs to inject the service, call the service object with the parameter, and send in a callback function:

angular.module('test', ['testaccount']).controller('TestCtrl', function ($scope, TestAccount) {
    $scope.selectedTestAccount = null;
    $scope.testAccounts = [];

    TestAccount.get(3, function (data) {
      $scope.testAccounts = data;
    })
}

Read more about service dependency injection in the tutorial.

like image 176
Foo L Avatar answered Nov 14 '22 00:11

Foo L