2016-05-23 7 views
0

私はデータを取得してコントローラに返すファクトリを持っています。最初のコントローラでは動作しますが、2番目のコントローラでは何も返しません。私はこれをすべてのコントローラーに渡すことができたという印象を受けました。 1分だけインスタンス化できると思っていたので、同じ手順で別のファクトリを作成しました。それと同じ結果。これは、そうでない場合は、あなたのオブジェクトは約束の実行前に返され、あなたがあなたの約束を返す必要があります

//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

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); }); } }; }); 

、その後は、あなたのコントローラで、あなたの約束を使用しています。明らかに、非同期コードが何であるかは分かりません。成功とエラーコールバックは後でイベント分と呼ばれ、すぐに結果を返します。それは動作しません。 – sielakos

答えて

1

第二のコントローラに空の配列が返されました。それはいけないと私は、それがすべてで働いていたことに驚いています

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

ありがとう!ちょうど私のアプローチを微調整し、それは働いた。どうもありがとう。 – JAME

関連する問題