Communicating between sibling scopes in Angular

前端 未结 2 1293
野趣味
野趣味 2021-01-01 21:45

Is this how to correctly communicate between two components that are scope siblings?

  1. Ctrl1 emits event up to parent scope of both Ctrl1 and Ctrl2.
  2. Par
2条回答
  •  悲哀的现实
    2021-01-01 22:25

    Well - you don't technically need $emit when communicating up to parent controllers, the child has access. But you do need $broadcast when communicating down to a child scope:

    app.controller("parentCtrl", function($scope) {
        $scope.testMe = function() {
            $scope.$broadcast("done"); //transmit to ctrl2
        }
    });
    
    app.controller("childCtrl1", function($scope) {
        $scope.testMe(); //call parent
    });
    
    app.controller("childCtrl2", function($scope) {
        $scope.$on("done", function() {
            alert("Caught parent event");
        });
    });
    

提交回复
热议问题