You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 1.5中如何在广播事件接收器内获取this对象?

在Angular 1.5广播事件接收器中获取控制器的this对象

哈哈,这个问题我在做Angular 1.5项目的时候踩过坑!其实核心原因是Angular的$scope.$on(或$rootScope.$on)回调函数里的this默认指向的是回调函数自身的上下文,而不是你的控制器实例,所以直接用this肯定拿不到你要的控制器属性/方法。给你几个靠谱的解决办法:

方法1:提前保存控制器的this到变量(最经典通用)

这是Angular 1.x里最常用的写法,先把控制器的this存到一个变量(比如vm,ViewModel的缩写)里,然后在回调中使用这个变量:

// 发送广播的控制器
angular.module('myApp').controller('SenderCtrl', function($rootScope) {
  var vm = this;
  vm.triggerBroadcast = function() {
    // 发送广播事件,附带数据
    $rootScope.$broadcast('userNotification', { content: '新消息来了!' });
  };
});

// 接收广播的控制器
angular.module('myApp').controller('ReceiverCtrl', function($scope) {
  var vm = this; // 关键:把控制器的this存下来
  vm.notification = '';

  // 监听广播事件
  $scope.$on('userNotification', function(event, payload) {
    // 用vm访问控制器的属性,而不是直接用this
    vm.notification = payload.content;
    console.log(vm.notification); // 输出"新消息来了!"
  });
});

方法2:用bind()绑定this到回调函数

你可以通过bind()方法,把控制器的this绑定到事件回调函数上,这样回调里的this就会指向控制器实例:

angular.module('myApp').controller('ReceiverCtrl', function($scope) {
  this.notification = '';

  $scope.$on('userNotification', function(event, payload) {
    this.notification = payload.content;
  }.bind(this)); // 把控制器的this绑定到回调
});

方法3:使用ES6箭头函数(项目支持ES6时推荐)

如果你的项目已经配置了Babel等工具支持ES6语法,箭头函数是更简洁的选择——箭头函数会自动继承外部作用域的this,也就是控制器的实例:

angular.module('myApp').controller('ReceiverCtrl', function($scope) {
  this.notification = '';

  // 箭头函数里的this就是控制器的this
  $scope.$on('userNotification', (event, payload) => {
    this.notification = payload.content;
  });
});

额外提醒

如果是用Angular 1.5的component语法,推荐在$onInit生命周期钩子中注册事件监听,上面的三种方法同样适用,比如:

angular.module('myApp').component('notificationReceiver', {
  controller: function($scope) {
    this.$onInit = function() {
      var vm = this;
      $scope.$on('userNotification', (event, payload) => {
        vm.notification = payload.content;
      });
    };
  },
  template: '<div>{{ $ctrl.notification }}</div>'
});

内容的提问来源于stack exchange,提问作者abbood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:34:18