1

我正在阅读本教程以在我的 Angular 1.5 应用程序中实现发送/接收广播消息。

所以在控制器里面我有这个:

  update(){
    this.$rootScope.$broadcast('language_changed');
  }

在另一个控制器中我得到了这个:

    $rootScope.$on('language_changed', function (event, data){
        this.updateStore();  <--- this here is undefined
    });

  }

  updateStore() {
      this.store = {
          ..
          language_id: this.LanguageService.get(),

        }
  }

我想知道如何才能掌握this广播内部。这个技巧没有奏效

4

2 回答 2

2

您提供的答案不是正确的解决方案,您需要了解自己在做什么,制作黑客不是解决方案。请阅读以下文章以了解有关 this 和 $scope this vs $scope之间区别的基本知识

重要的是要了解有关角度事件:

$emit - 将事件向上发送到范围的三个角度

$broadcast - 将事件发送到三角

此外,请查看以下代码段:代码段

当您有两个控制器时,您不需要同时从 $rootScope 广播事件并在 $rootScope 上监听它,它可以简单地在 $scope 级别上监听,不需要 $rootScope 依赖注入。查看以下内容:

app.controller('DemoCtrl', function($scope, $rootScope) {
  $scope.broadCastEvent = function() {
    $rootScope.$broadcast('language_changed');
  };
});

假设我们想在用户单击按钮时广播一个事件。该事件被发送到范围的三个角度,因此正在侦听此事件的控制器可以在范围级别上侦听它,而无需 $rootScope 依赖注入,如下所示:

app.controller('DemoCtrl2', function($scope) {
  $scope.$on('language_changed', function() {
   $scope.eventFired = !$scope.eventFired;
   });
})

另一种情况是当您想要 $emit 事件(将其发送到角度三)时,您需要将 $rootScope 注入将侦听该事件的控制器,因为只有 $rootScope 可以侦听正在从 $rootScope 进行$ emited。查看以下内容:

控制器$发射事件:

app.controller('DemoCtrl', function($scope, $rootScope) {
 $scope.emitEvent = function() {
  $rootScope.$emit('language_changed');
 };
});

控制器捕获事件:

app.controller('DemoCtrl2', function($scope, $rootScope) {
  $rootScope.$on('language_changed', function() {
   $scope.eventFired = !$scope.eventFired;
 });
})

试着玩一下这个片段,如果你想从 $rootScope 中 $emit 事件并尝试在 $scope 级别上捕获它,看看会发生什么。

希望这能澄清一点。

于 2018-02-12T14:25:43.980 回答
1

解决方案很简单,使用 javascript bindhack:

$rootScope.$on('language_changed', function (event, data){
    this.updateStore();
}.bind(this));  <-- bind makes the inner this same as outer this.. 
于 2018-02-09T06:21:46.320 回答