Reputation: 115
How can I move this function from the controller into a separate file?
It might be a simple question but I tried to do that with services and factories but I keep doing something wrong regarding dependency injection or the syntax of the service or factory.
This is the controller:
angular.module("myApp", [])
.controller('myAppCtrl', function ($scope, $http) {
(function() {
//the function to be moved
//do somthing
})();
$scope.data = {};
$http.//......do something else
});
Upvotes: 0
Views: 93
Reputation: 4974
plunkr: (Replaced real API link at request of OP)
HTML:
<div ng-app="myApp">
<div ng-controller="myAppCtrl">
<ul>
<li ng-repeat="product in data.products" ng-bind="product.name"></li>
</ul>
</div>
</div>
Javascript:
angular.module("myApp", [])
.constant("dataUrl", "https://some-link.com")
.controller('myAppCtrl', function($scope, corsService) {
$scope.data = {};
corsService.getData().then(function(data) {
$scope.data.products = data;
}).catch(function(error) {
$scope.data.error = error;
});
});
angular.module("myApp")
.factory('corsService', function($http, dataUrl) {
return {
getData: getData
}
function corsRequestEnabler() {
//Enable CORS requests
};
function getData() {
corsRequestEnabler();
return $http.get(dataUrl)
.then(function(response) {
console.log('Response', response);
return response.data;
}, function(error) {
return error
})
}
});
Upvotes: 1
Reputation: 1718
var app=angular.module("myApp", []);
app.controller('myAppCtrl', function (corsService, $scope, $http, dataUrl ) {
corsService();
app.factory('corsService' ,function($http){
var data = {};
$http.get(dataUrl)
.success(function (data) {
data.products = data;
console.log(data);
})
.error(function (error) {
data.error = error;
});
return data;
});
});
Upvotes: 0