使用 $scope.$emit() 在组件之间传递数据

pass data between components with $scope.$emit()

我正在尝试在具有相同父组件的两个组件之间传递数据(简单版本:我有 child1 组件、child2 组件,它们都是父组件的子组件)。此外,所有组件都是控制器。

父组件也是根组件(它没有任何父组件)所以我想我必须使用 $rootScope

如果我想将 var myVar(整数)从 child1 传递给 child2,我想我应该这样做:

在 child1 组件中:

$rootScope.$emit('myEvent', vm.myVar);

在父组件中:

$scope.$on('changeTab', function(){
   console.log('parent', vm.myVar);
});
$scope.$broadcast('changeTab', vm.myVar);

在 child2 组件中:

$rootScope.$on('changeTab', function () {
    console.log('child2', vm.myVar);
});

我是新手,不明白为什么这不起作用,可能没什么大不了的,如果有人能帮助我,我将不胜感激:) ty !

顺便说一下,我在两个控制台日志中都得到了 "undefined",但是 myVar 在 child1 中被正确定义了。

您需要广播给 child 的 parent:

$scope.$parent.$broadcast('hi', {
    msg: 'Hello there!'
});

$scope.$broadcast 沿着链发送消息,但是如果您广播到作用域的 parent 那么 parent 将向下发送消息,其中包括 兄弟姐妹。

angular.module('appModule', [])
  .controller('ParentController', [function() {
    this.hello = 'I am the parent';
  }])
  .controller('Child1Controller', ['$scope', function($scope) {
    this.hello = 'I am Child 1';
    var that = this;
    $scope.$on('hi', function(event, data) {
      console.log(data.msg);
      that.hello = data.msg;
    });
  }])
  .controller('Child2Controller', ['$scope', function($scope) {
    this.hello = 'I am Child 2';
    this.sayHello = function(str) {
      $scope.$parent.$broadcast('hi', {
        msg: str
      });
    }
  }]);

angular.bootstrap(window.document, ['appModule'], {
  strictDi: true
});
div {
  border: 1px dotted #f00;
  padding: 15px;
}
<div ng-controller="ParentController as parentCtrl">
  <p>{{parentCtrl.hello}}</p>
  <div ng-controller="Child1Controller as child1Ctrl">
    <p>{{child1Ctrl.hello}}</p>
  </div>
  <div ng-controller="Child2Controller as child2Ctrl">
    <p>{{child2Ctrl.hello}}</p>
    <button type="button>" ng-click="child2Ctrl.sayHello('Child 2 is cool')">Say Hello to Child 1</button>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>