最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Communicating between sibling scopes in Angular - Stack Overflow

programmeradmin3浏览0评论

Is this how to correctly municate between two ponents that are scope siblings?

  1. Ctrl1 emits event up to parent scope of both Ctrl1 and Ctrl2.
  2. Parent scope listens for emitted event from Ctrl1, then broadcasts another event down to Ctrl2.
  3. Ctrl2 listens for broadcasted event from parent scope.

Is this how to correctly municate between two ponents that are scope siblings?

  1. Ctrl1 emits event up to parent scope of both Ctrl1 and Ctrl2.
  2. Parent scope listens for emitted event from Ctrl1, then broadcasts another event down to Ctrl2.
  3. Ctrl2 listens for broadcasted event from parent scope.

Share Improve this question asked Dec 30, 2014 at 17:23 corecore 33.1k45 gold badges140 silver badges195 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Yes, this is how I municate between sibling scopes in Angular. Typically I think of Ctrl1 as emitting 'up' to all its descendant scopes and 'on' a parent scope listening to the event, the parent scope broadcasting 'down' to all children scopes. In this case, Ctrl2 should have something set up on 'on' to do something once it hears the event.

As a side note, I've done something similar where I've used the rootScope as a centralized event bus where it listens to different children scope's events and then performs some task or broadcasts down again. The children scopes would then be responsible for simply emitting up to the rootScope.

Well - you don't technically need $emit when municating up to parent controllers, the child has access. But you do need $broadcast when municating 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");
    });
});
发布评论

评论列表(0)

  1. 暂无评论