0
votes

little problem here, i have a controller which communicate with factories, but how can i pass the factory result to a function? Something i tried:

.controller('testCtrl', ['$scope', 'foo', 'boo', function($scope, foo, boo){

     foo.get().then(function(response){
          $scope.foo = response;   
     });

     boo.get().then(function(response){
          $scope.boo = response;   
     });

     // Why this will not work?
     function test(){
          var getFoo = $scope.foo;
          var getBoo = $scope.boo; 
     };

}]

Example above is not working, how can i get this work?

Thanks.

1
Define "will not work". You're using asynchronous code. That's like putting bread in a toaster and continue doing things while the bread is being toasted. You can't expect to have toasted bread right after you have pushed the toaster button. You'll only have toasted bread when the toaster dings, i.e. when the function passed to then() has been executed. - JB Nizet
Will not work = Response will not be passed. Thanks for toaster explanation, i found a solution :) - Jack
Then it works - the response will be passed. - fdreger

1 Answers

0
votes

To guys who came after the party. A working example without using $scope.

hoge.controller('testCtrl', ['$scope', 'foo', 'boo', function($scope, foo, boo){
  function test() {
     var getFoo = null;
     var getBoo = null; 

     Promise.all([foo.get(), boo.get()]).then(function(results) {
       getFoo = results[0];
       getBoo = results[1];
     });
   };
}]