Dan Romulus Dan Romulus - 1 year ago 56
AngularJS Question

Angularjs moving logic from the controller

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


Answer Source

plunkr: (Replaced real API link at request of OP)


<div ng-app="myApp">
  <div ng-controller="myAppCtrl">
    <li ng-repeat="product in data.products" ng-bind="product.name"></li>


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;

  .factory('corsService', function($http, dataUrl) {
    return {
      getData: getData

    function corsRequestEnabler() {
      //Enable CORS requests

    function getData() {
      return $http.get(dataUrl)
        .then(function(response) {
          console.log('Response',  response);
          return response.data;
        }, function(error) {
          return error
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download