AngularJS directive that uses the original element type in template

前端 未结 1 913
醉梦人生
醉梦人生 2021-01-02 06:43

I\'m developing UI and typography based directives for Angular. In such cases, the element the directive is being applied on is unknown - anything from a div, span, h1 to an

相关标签:
1条回答
  • 2021-01-02 07:16

    I've been mulling over this question for a couple weeks now until I realised that template could be a function with the ability to access element and attrs. Thus I was able to return a template with the existing element tags.

    module.directive( 'myDir', [ '$window', function( $window ) {
        return {
            restrict: "A",
            template: function( element, attrs ) {
                var tag = element[0].nodeName;
                return "<"+tag+" data-ng-transclude ng-*=''></"+tag+">";
            },
            transclude: true,
            replace: true,
            link: function ( scope, element, attrs ) {
    
            }
        }   
    }]);
    

    HTML

    <div data-my-dir>
        <span>some other stuff</span>
        <div>more stuff</div>
    </div>
    
    <span data-my-dir></span>
    
    <h1 data-my-dir></h1>
    

    Output

    <div ng-*="" data-ng-transclude="" data-my-dir="">
        <span class="ng-scope">some other stuff</span>
        <div class="ng-scope">more stuff</div>
    </div>
    
    <span ng-*="" data-ng-transclude="" data-my-dir=""></span>
    
    <h1 ng-*="" data-ng-transclude="" data-my-dir=""></h1>
    
    0 讨论(0)
提交回复
热议问题