在AngularJS中,当使用“controller as”语法和“this”时,如何在promise的回调中引用“this”?

时间:2014-11-11 18:27:17

标签: angularjs scope angularjs-scope promise

我在then()中返回了一些数据,我需要将其存储在"这个"变量。由于它没有被存储在范围内,并且因为它被包裹在回调中,我的控制器"这个"无效。如何将数据冒泡回来,以便将其存储在内部"这个"?见下文:

angular.module('logisticsApp.controllers').
controller('InventoryCtrl', ['$scope', '$http', '$window', 'DataService', 
    function ($scope, $http, $window, DataService) {

    this.inventory = ''; // need to have data stored here

    $scope.$on('$viewContentLoaded', angular.bind(this, function() {
      // "this" is still valid here
      myService.getInventory().then(function(data) {
        // "this" is no longer valid!
        $scope.inventory = data; // so this fails
      });
    }));
}]);

1 个答案:

答案 0 :(得分:9)

您可以使用angular.bind

myService.getInventory().then(angular.bind(this, function(data) {
  console.log(this.inventory);
}));

来自angular.bind docs

  

返回一个函数,该函数调用绑定到self的函数fn(self成为fn的 this )。


您也可以保存对上下文(this)的引用,如下所示:

var self = this;

myService.getInventory().then(function(data) {
  console.log(self.inventory);
});