Communicating with sibling directives

后端 未结 6 545
余生分开走
余生分开走 2021-01-31 10:19

Goal: Create behaviors using directives with communication between 2 sibling elements (each their own directive).

A behavior to use in example: The article content is hi

6条回答
  •  日久生厌
    2021-01-31 10:38

    The above solutions are great, and you should definitely consider using a parent scope to allow communication between your directives. However, if your implementation is fairly simple there's an easy method built into Angular that can communicate between two sibling scopes without using any parent: $emit, $broadcast, and $on.

    Say for example you have a pretty simple app hierarchy with a navbar search box that taps into a complex service, and you need that service to broadcast the results out to various other directives on the page. One way to do that would be like this:

    in the search service

    $rootScope.$emit('mySearchResultsDone', {
      someData: 'myData'
    }); 
    

    in some other directives/controllers

    $rootScope.$on('mySearchResultsDone', function(event, data) {
      vm.results = data;
    });
    

    There's a certain beauty to how simple that code is. However, it's important to keep in mind that emit/on/broadcast logic can get nasty very quickly if you have have a bunch of different places broadcasting and listening. A quick google search can turn up a lot of opinions about when it is and isn't an anti-pattern.

    Some good insight on emit/broadcast/on in these posts:

    • http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

    • http://nathanleclaire.com/blog/2014/04/19/5-angularjs-antipatterns-and-pitfalls/

提交回复
热议问题