How do I share data between sibling components in angular?

前端 未结 4 1310
轮回少年
轮回少年 2021-02-04 08:08

I have an Angular application with 3 sibling components, they are able to access and update the variable \"data\". They are connected to the router, but the data I want to pass

4条回答
  •  攒了一身酷
    2021-02-04 08:45

    Angular has the facility to share data between siblings through $emit, $broadcast and $on in angular’s $scope and $rootScope event system.

    // SiblingOneCtrl
    // SiblingTwoCtrl

    app.controller('SiblingOneCtrl1',
      function SiblingOneCtrl1 ($rootScope) {
    
      $rootScope.$on('rootScope:emit', function (event, data) {
        console.log(data); // 'Emit!'
      });
    
      $scope.$on('rootScope:broadcast', function (event, data) {
        console.log(data); // 'Broadcast!'
      });
    
      $rootScope.$on('rootScope:broadcast', function (event, data) {
        console.log(data); // 'Broadcast!'
      });
    
    });
    
    app.controller('SiblingOneCtrl2',
      function SiblingOneCtrl2($rootScope) {
    
      $rootScope.$emit('rootScope:emit', 'Emit!'); // $rootScope.$on
      $rootScope.$broadcast('rootScope:broadcast', 'Broadcast'); // $rootScope.$on && $scope.$on
    
    });
    

    also, you can follow this and this

提交回复
热议问题