2016-05-23 76 views
0

我有一個工廠正在獲取數據並將其返回給控制器。它在第一個控制器上工作,但在第二個控制器上沒有任何返回。我的印象是,我可以把它傳遞給所有的控制器。一會兒,我想也許它只能被實例化一次,所以我用相同的步驟創建了另一個工廠。還是一樣的結果。它在第二控制器

//Factory 
 

 
angular.module('myApp') 
 
    .factory('classData', function($http){ 
 

 
     return { 
 

 
     getClassData : function() { 
 

 
      var studentData = [ ]; 
 

 
      $http({ 
 
      method: 'GET', 
 
      url: 'theUrl' 
 
      }).success(function(data){ 
 

 
      for(var i = 0; i < data.length; i++) 
 
       studentData.push(data[i]); 
 

 
      }).error(function(){ 
 
      alert("error", error); 
 
      }); 
 

 
      return studentData; 
 

 
     } 
 
     }; 
 
    }); 
 

 

 
//Controller 1: 
 

 
angular.module('myApp') 
 
    .controller('studentListCtrl', function($scope, classData, statService) { //this controller is just view logic 
 

 
    $scope.sortType  = 'attendanceYtd'; 
 
    $scope.searchStudent = ''; 
 
    $scope.students = classData.getClassData(); //returns all \t \t data 
 
\t 
 
//Controller 2: 
 

 
angular.module('attendanceApp') 
 
    .controller('studentHistoryCtrl', function($scope, $stateParams, classData) { 
 
    //get all data 
 
    $scope.students = classData.getClassData(); 
 
    console.log($scope.students); //returning an empty array

+1

我很驚訝它的工作在所有的,因爲它不應該。顯然你不明白什麼是異步代碼。成功和錯誤回調可以在事件分鐘後被調用,並且您立即返回結果。它不應該工作。 – sielakos

回答

1

你必須返回你的諾言返回一個空數組,否則你的對象是在承諾的執行前返回。

angular.module('myApp') 
    .factory('classData', function($http){ 

     return { 

     getClassData : function() { 

      var studentData = [ ]; 

      return $http({ 
      method: 'GET', 
      url: 'theUrl' 
      }).then(function(data){ 
      for(var i = 0; i < data.length; i++) 
       studentData.push(data[i]); 
      return studentData; 
      }, function(){ 
      alert("error", error); 
      }); 


     } 
     }; 
    }); 

,然後在你的控制器,使用您的承諾:

classData.getClassData().then(function(results){ 
    $scope.students = result; 
}); 
+0

謝謝!只是調整了我的方法,它的工作。非常感謝。 – JAME