Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
AngularJS使用get正确获取json_Angularjs - Fatal编程技术网

AngularJS使用get正确获取json

AngularJS使用get正确获取json,angularjs,Angularjs,我已经能够使用下面的内容来获取jSON,这很好,但是有人告诉我,使用工厂和服务将是一个更好的选择。就我的一生而言,我无法让任何东西工作,我甚至不明白为什么我应该使用工厂 有人能告诉我为什么或者至少帮我一把吗?这里我的主要要求是获取jSON,然后将其传递到每个对象的列表中(我还没有尝试让它工作) 如果您想在另一个控制器中进行相同的服务器调用,该怎么办。你会复制并粘贴相同的$http.get(…代码吗?不,当然不会,因为那会是一种非常糟糕的代码味道,也是干(不要重复)违规的主要例子 这就是为什么您的

我已经能够使用下面的内容来获取jSON,这很好,但是有人告诉我,使用工厂和服务将是一个更好的选择。就我的一生而言,我无法让任何东西工作,我甚至不明白为什么我应该使用工厂

有人能告诉我为什么或者至少帮我一把吗?这里我的主要要求是获取jSON,然后将其传递到每个对象的
  • 列表中(我还没有尝试让它工作)


    如果您想在另一个控制器中进行相同的服务器调用,该怎么办。你会复制并粘贴相同的
    $http.get(…
    代码吗?不,当然不会,因为那会是一种非常糟糕的代码味道,也是干(不要重复)违规的主要例子

    这就是为什么您的
    $http
    需要进入一个单独的函数(称之为“服务”或“工厂”),您可以从任何地方调用它

    theApp.controller('MenuSideController', [
      '$scope',
      'CategoryService',
      function ($scope, CategoryService){
        CategoryService.getList()
          .success(function(list){
            $scope.list = list;
          });
    
      }
    ]);
    
    theApp.factory('CategoryService', [
      '$http',
      function($http){
        return {
          getList: function(){
            return $http.get('/directory/assets/inc/category.php');
          }
        };
      }
    
    ]);
    
    theApp.controller('MenuSideController', [
      '$scope',
      'CategoryService',
      function ($scope, CategoryService){
        CategoryService.getList()
          .success(function(list){
            $scope.list = list;
          });
    
      }
    ]);
    
    theApp.factory('CategoryService', [
      '$http',
      function($http){
        return {
          getList: function(){
            return $http.get('/directory/assets/inc/category.php');
          }
        };
      }
    
    ]);