2014-02-26 35 views
0

我正在使用角度js爲一個項目,我有兩個控制器。新客戶在newCustomerController中創建,我需要訪問另一個控制器中的客戶詳細信息。我正在使用工廠來執行上述請求。Angularjs服務不斷收到對象不是函數錯誤

但我不斷收到錯誤TypeError:object不是addCustomer函數的函數。

我廠如下

app.factory('mySharedService',function($rootScope){ 
    var sharedService = {}; 

    sharedService.customer = {}; 

    sharedService = { 

     prepLoadAddress : function(customer){ 
     this.customer = customer; 
     $this.loadAddress(); 
     }, 

     loadAddress : function(){ 
     $rootScope.$broadcast('handleLoadAddress'); 
     } 
    }; 
    return sharedService; 
}); 

我的第一個控制器,如下

function newCustomerController($scope,$http){ 
    $scope.name = "John Smith"; 
    $scope.email = "John Smith"; 
    $scope.contact = "John Smith"; 
    $scope.address = "John Smith"; 
    $scope.comment = "John Smith"; 
    $scope.archived = 0; 

    $scope.addCustomer = function() { 

     $http({ 
      method: 'POST', 
      url: '/customers/createCustomer', 
      params: { 
       name: $scope.name, 
       email: $scope.email, 
       contact: $scope.contact, 
       delivery_comment: $scope.comment, 
       archived: $scope.archived 
      } 
     }).success(function(result) { 
      $scope.name = ""; 
      $scope.email = ""; 
      $scope.contact = ""; 
      $scope.address = ""; 
      $scope.comment = ""; 
      $scope.archived = 0; 

      mySharedService.prepLoadAddress(result); 
     }); 
    }; 
} 

該控制器創建客戶。成功後,它將爲另一個控制器中的客戶設置範圍。我下面

function bController($scope, $http) { 
$scope.customer = {}; 
    $scope.load_customer = function() { 

    if ($scope.customer_id != null) { 
     $http({ 
      method: 'GET', 
      url: '/customers/customer', 
      params: { 
       id: $scope.customer_id 
      } 
     }).success(function(result) { 
      $scope.customer = result; 
      $scope.address_id = result.address.id; 
      $scope.address = result.address; 
     }); 
    } 
}; 

$scope.$on('handleLoadAddress',function(events,customer){ 
    $scope.customer = mySharedService; 
}); 
}; 

控制器做了注射以及

newCustomerController.$inject = ['$scope','mySharedService']; 
newWaypointController.$inject = ['$scope','mySharedService']; 

任何人都可以幫助我?提前致謝!

回答

2

首先

app.factory('mySharedService',function($rootScope){ 
    var sharedService = {}; 

    sharedService.customer = {}; 

    sharedService = {   <-- here you assign new object to sharedService, so there is no sense in previous two lines. 

    prepLoadAddress : function(customer){ 
     this.customer = customer; 
     $this.loadAddress(); 
    }, 

    loadAddress : function(){ 
     $rootScope.$broadcast('handleLoadAddress'); 
    } 
    }; 
    return sharedService; 
}); 

我沒有在你的控制器注入mySharedService

function newCustomerController($scope,$http, mySharedService){ 
function bController($scope, $http, mySharedService) { 

的看到這裏,你可能要分配客戶?

$scope.$on('handleLoadAddress',function(events,customer){ 
    $scope.customer = mySharedService.customer; 
}); 
+0

謝謝!這些變化是我錯過的 – edelweiss

相關問題