Angular - 将变量公开给Controller

时间:2016-11-11 18:34:00

标签: angularjs scope controller factory encapsulation

所以我有一个控制器调用工厂,然后设置一个“variableToExpose”。当我将console.log($ scope.variableToExpose)显示为未定义时。什么是将该变量暴露给控制器的最佳方法?

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

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

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

谢谢!

1 个答案:

答案 0 :(得分:2)

console.log移到成功处理程序中。

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

promise的.then方法在promise解决后调用成功处理函数。 $q服务调用该函数,并将promise的已解析值作为唯一参数。