1

我正在从角度服务获取休息 api 调用,我需要在角度控制器的任何变量中获取响应数据。所以我可以在视图文件中使用它。这是我的代码:

我的角度 service.js:

  angular.module('customerdetails').factory('Detail',['$resource', 
     function($resource){
       return new Customerdetails($resource);
  }]);

  function Customerdetails( resource ) {                         
     this.getUsers = function( scope ) {
       var Customerdetails = resource('/customerdetails');
       Customerdetails.query(function(users){       
           scope.Customerdetails = users;
       });
     }
  }

我的角度控制器:

  angular.module('customerdetails').controller('CustomerController', 
    ['$scope', '$rootScope',  'Authentication', 'Detail', 
    function ($scope,   $rootScope, Authentication, Detail) {
        $scope.authentication = Authentication;
        $scope.users = [];

        $scope.find = function(){
        Detail.getUsers( $scope ) 
          .success(function (custs) {
                $scope.customers = custs;
            })
            .error(function (error) {
                $scope.status = 'Unable to load customer data: ' + error.message;
            });

        //console.log(users,"ppppppp");
       };
      } ]);

在此我在我的restapi中获取详细信息。当我需要从控制器获取数据以便传入视图文件(html)时,它显示 Detail.getUsers 未定义。

有什么帮助吗?

4

2 回答 2

0

我以前也遇到过类似的问题。我的解决方案是将工厂和服务结合起来。像这样:

//Factory
angular.module('customerdetails').factory('Detail',['$resource', function($resource){
    return $resource('/customerdetails');
}]);

// Service
angular.module('customerdetails').service('DetailService', ['Detail', function (Detail) {
    this.getUsers = function(success, error){
        return Detail.query().$promise.then(success).catch(error);
    }    
}]);

从这里,您可以在控制器中注入您的服务。

// Controller
angular.module('customerdetails').controller('CustomerController',['$scope', '$rootScope',  'Authentication', 'DetailService', function ($scope,   $rootScope, Authentication, DetailService) {
    $scope.authentication = Authentication;
    $scope.users = [];

    $scope.find = function(){
        DetailService.getUsers(function(custs){
            $scope.customers = custs;
        }, function(error){
            $scope.status = 'Unable to load customer data: ' + error.message;
        });
    };
  }]);
于 2015-11-24T16:44:34.123 回答
0
angular.module('customerdetails').factory('Detail',['$resource', 
  var  getUsers = function(resource) {
    console.log('getUsers')
  };

  return {
    getUsers : getUsers
  }
])
于 2015-11-24T13:11:23.147 回答