Andres Andres - 21 days ago 6
AngularJS Question

Angular - Expose variable to Controller

So I have a controller that makes a call to a factory and then sets a "variableToExpose". When I console.log($scope.variableToExpose) is comes up as undefined. Whats the best way to expose that variable to the controller?

.controller('SomeCtrl', function($scope, $http, $state, SomeFactory) {

console.log($scope.variableToExpose); //returns undefined

SomeFactory.getRequest($id).then(function(response){
$scope.variableToExpose = varFromGetRequest;
}
}


Thanks!

Answer

Move the console.log inside the success handler.

app.controller('SomeCtrl', function($scope, $http, $state, SomeFactory) {


  //console.log($scope.variableToExpose); //returns undefined

  SomeFactory.getRequest($id).then(function successHandler(response){
      //$scope.variableToExpose = varFromGetRequest;
      $scope.variableToExpose = response;
      console.log($scope.variableToExpose);
  });
});

The .then method of a promise invokes the success handler function after the promise has resolved. The $q service invokes that function with the resolved value of the promise as the only argument.

Comments