Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - add HTML element to dom in directive without jQuery

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: function (scope, iElement, iAttrs) {      var svgTag = $('<svg width="600" height="100" class="svg"></svg>');     $(svgTag).appendTo(iElement[0]);      ...     } 

Yet I don't want the directive to depend on jQuery for this simple task. How would I accomplish the same with AngularJS means (or native JavaScript code).

like image 221
dorjeduck Avatar asked Oct 21 '13 07:10

dorjeduck


2 Answers

Why not to try simple (but powerful) html() method:

iElement.html('<svg width="600" height="100" class="svg"></svg>'); 

Or append as an alternative:

iElement.append('<svg width="600" height="100" class="svg"></svg>'); 

And , of course , more cleaner way:

 var svg = angular.element('<svg width="600" height="100" class="svg"></svg>');  iElement.append(svg); 

Fiddle: http://jsfiddle.net/cherniv/AgGwK/

like image 199
Ivan Chernykh Avatar answered Oct 11 '22 18:10

Ivan Chernykh


In angularJS, you can use angular.element which is the lite version of jQuery. You can do pretty much everything with it, so you don't need to include jQuery.

So basically, you can rewrite your code to something like this:

link: function (scope, iElement, iAttrs) {   var svgTag = angular.element('<svg width="600" height="100" class="svg"></svg>');   angular.element(svgTag).appendTo(iElement[0]);   //... } 
like image 42
Dzung Nguyen Avatar answered Oct 11 '22 18:10

Dzung Nguyen