Communicating with sibling directives

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

    I had the exact same problem and I was able to solve it.

    In order to get one directive to hide other sibling directives, I used a parent directive to act as the API. One child directive tells the parent it wasn't to be shown/hidden by passing a reference to its element, and the other child calls the parent toggle function.

    http://plnkr.co/edit/ZCNEoh

    app.directive("parentapi", function() {
      return {
        restrict: "E",
        scope: {},
        controller: function($scope) {
          $scope.elements = [];
    
          var on = true;
          this.toggleElements = function() {
            if(on) {
              on = false;
              _.each($scope.elements, function(el) {
                $(el).hide();
              });
            } else {
              on = true;
              _.each($scope.elements, function(el) {
                $(el).show();
              });
            }
          }
    
          this.addElement = function(el) {
            $scope.elements.push(el);
          }
        }
      }
    });
    
    app.directive("kidtoggle", function() {
      return {
        restrict: "A",
        require: "^parentapi",
        link: function(scope, element, attrs, ctrl) {
          element.bind('click', function() {
            ctrl.toggleElements();  
          });
        }
      }
    });
    
    app.directive("kidhide", function() {
      return {
        restrict: "A",
        require: "^parentapi",
        link: function(scope, element, attrs, ctrl) {
          ctrl.addElement(element);
        }
      }  
    });
    

提交回复
热议问题