【问题标题】:In AngularJS, when using "controller as" syntax and "this", how to reference "this" inside a promise's callback?在AngularJS中,当使用“controller as”语法和“this”时,如何在promise的回调中引用“this”?
【发布时间】:2015-01-08 09:52:51
【问题描述】:

我在 then() 中返回了一些数据,我需要将这些数据存储在“this”变量中。由于它没有存储在范围内,并且由于它被包装在回调中,因此我的控制器的“this”无效。如何备份数据以便将其存储在“this”中?见下文:

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

【问题讨论】:

标签: angularjs scope angularjs-scope promise


【解决方案1】:

你可以使用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);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 2017-01-29
    • 2017-12-25
    • 1970-01-01
    相关资源
    最近更新 更多