在角度控制器中调用工厂功能

时间:2015-11-24 12:53:39

标签: angularjs angularjs-scope angular-resource angular-controller

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

my angular 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。

任何帮助?

2 个答案:

答案 0 :(得分:0)

ASSERT failure in QVector<T>::operator[]: "index out of range",

答案 1 :(得分: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;
        });
    };
  }]);