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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With