加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在AngularJS中,当使用“controller as”语法和“this”时,如何在

发布时间:2020-12-17 17:53:26 所属栏目:安全 来源:网络整理
导读:我在then()中返回了一些数据,我需要将它存储在“this”变量中.因为它没有存储在范围内,并且因为它包含在回调中,所以我的控制器的“this”无效.如何将数据冒泡,以便将其存储在“this”中?见下文: angular.module('logisticsApp.controllers').controller('I
我在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
      });
    }));
}]);

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读