简体   繁体   中英

Insert directive template after another element when this one is clicked

I'm working on a custom directive. This is what I have:

<button myDirective>Click Me</button>

My directive looks like this:

return {
  restrict: 'EA',
  controller: 'Controller',
  replace: false,
  template: '<h3>Test</h3>', // actually more complex
  link: function( $scope, $element, $attrs ) {
    $element.on( 'click', function() {
      // code, that shows the template
    });
  }
};

Result is:

<button myDirective>Click Me
  <h3>Test</h3>
</button>

But i want to have something like this:

<button myDirective>Click Me</button>
<h3>Test</h3> <!-- just shown after button is clicked -->

After the button is clicked the template should be shown after the button.

Thank you.

I would suggest rendering the button in directive template. Here's an example snippet:

 angular.module('myApp', []) .directive('expander', function() { return { restrict: 'EA', replace: true, template: '<div><button ng-click="showContent=true">{{buttonText}}</button><h3 ng-show="showContent">Test</h3></div>', link: function( $scope, $element, $attrs ) { $scope.buttonText = $attrs.text; } } }); 
 <html ng-app="myApp"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script> </head> <body> <expander text="Press me"></expander> </body> </html> 

You can use jqLite's .after() to append the content after any element the directive is attached to, then hide and show the content on click.

View:

<button my-directive>Click Me!</button>

Directive:

return {
  restrict: 'EA',
  scope: {
    time: '='
  },
  link: function($scope, $element){
    var afterStuff = angular.element('<h3 style="display:none;">Test</h3>');

    $element.after(afterStuff);
    //full jquery version
    $element.on('click', function(){
      afterStuff.toggle();
    });
  }
}

JSBin: https://jsbin.com/xuwuhu/edit?html,js,output

在按钮处理程序中解除标记后,可以使用ngif或ngshow显示内容。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM