Dan Romulus Dan Romulus - 4 months ago 15
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

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