Andres Andres - 3 months ago 22
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

$scope.variableToExpose = varFromGetRequest;



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;

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.