Angularjs从控制器移动逻辑

时间:2016-08-04 09:11:57

标签: angularjs dependency-injection angular-services

如何将此功能从控制器移动到单独的文件中?

这可能是一个简单的问题,但我尝试用服务和工厂做到这一点,但我一直在做依赖注入或服务或工厂语法方面的错误。

这是控制器:



angular.module("myApp", [])
.controller('myAppCtrl', function ($scope, $http) {

    (function() {
        //the function to be moved
        //do somthing
    })();

    $scope.data = {};

    $http.//......do something else

});




2 个答案:

答案 0 :(得分:1)

plunkr :(根据OP的要求替换了真实的API链接)

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

答案 1 :(得分:0)

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

});