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

标签 angularjs scope angularjs-scope promise

我在 then() 中返回了一些数据,我需要将这些数据存储在“this”变量中。由于它没有存储在范围内,并且由于它包含在回调中,因此我的 Controller 的“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
      });
    }));
}]);

最佳答案

您可以使用 angular.bind :

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

来自 angular.bind docs :

Returns a function which calls function fn bound to self (self becomes the this for fn).



您还可以像这样保存对上下文(this)的引用:
var self = this;

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

关于angularjs - 在 AngularJS 中,当使用 "controller as"语法和 "this"时,如何在 promise 的回调中引用 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26871836/

相关文章:

clojure - 如何在 Clojure 宏的词法范围内捕获?

javascript - $broadcast 不从服务中触发 (AngularJS)

visual-studio - 在 Visual Studio 中缩小和捆绑 AngularJS

javascript - AngularJS 路由页面未显示

javascript - $routeParams 中的参数未定义,但 $routeParams 未定义

C++ - 函数范围内的函数声明?

sql - Rails ActiveRecord 中的复杂连接

javascript - 在 Angularjs 中没有 $scope 范围对象不会改变

angularjs - 上传文件并发送数据 AngularJS + WebAPI

javascript - 使用 AngularJS 进行 SPA 设计 - 在一些但不是所有页面之间共享状态