AngularJS - add HTML element to dom in directive without jQuery

前端 未结 4 1505
逝去的感伤
逝去的感伤 2021-01-31 02:35

I have an AngularJS directive in which I want to add a svg tag to the current element of the directive. Right now I do this with the help of jQuery

link: functio         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-31 03:06

    If your destination element is empty and will only contain the tag you could consider using ng-bind-html as follow :

    Declare your HTML tag in the directive scope variable

    link: function (scope, iElement, iAttrs) {
    
        scope.svgTag = '';
    
        ...
    }
    

    Then, in your directive template, just add the proper attribute at the exact place you want to append the svg tag :

    
    ...
    
    

    Don't forget to include ngSanitize to allow ng-bind-html to automatically parse the HTML string to trusted HTML and avoid insecure code injection warnings.

    See official documentation for more details.

提交回复
热议问题