Communicating with sibling directives

后端 未结 6 564
余生分开走
余生分开走 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:51

    None of the directive require options will allow you to require sibling directives (as far as I know). You can only:

    • require on the element, using require: "directiveName"
    • tell angular to search up the DOM tree using require: "^directiveName"
    • or require: "^?directiveName" if you don't necessarily need the parent controller
    • or require: "^\?directiveName" if you don't necessarily need the parent DOM wrapper

    If you want sibling to sibling communication, you'll have to house them in some parent DOM element with a directive controller acting as an API for their communication. How this is implemented is largely dependent on the context at hand.

    Here is a good example from Angular JS (O Reilly)

    app.directive('accordion', function() {
      return {
        restrict: 'EA',
        replace: true,
        transclude: true,
        template: '
    ', controller: function() { var expanders = []; this.gotOpened = function(selectedExpander) { angular.forEach(expanders, function(expander) { if(selectedExpander != expander) { expander.showMe = false; } }); }; this.addExpander = function(expander) { expanders.push(expander); } } } }); app.directive('expander', function() { return { restrict: 'EA', replace: true, transclude: true, require: '^?accordion', scope: { title:'@' }, template: '
    \n
    {{ title }}
    \n
    \n
    ', link: function(scope, element, attrs, accordionController) { scope.showMe = false; accordionController.addExpander(scope); scope.toggle = function toggle() { scope.showMe = !scope.showMe; accordionController.gotOpened(scope); } } } })

    Usage (jade templating):

    accordion
        expander(title="An expander") Woohoo! You can see mme
        expander(title="Hidden") I was hidden!
        expander(title="Stop Work") Seriously, I am going to stop working now.
    

提交回复
热议问题