AngularJS: How to return the original element with a new sibling element in the directive?

Given this markup:

<a href="/" myDirective="Text 1 2 3 Foo">Link</a> 

How can I end this conclusion with a directive?

 <a class="tooltip" style="left:<the left pos of the original element>; top:<the top pos of the original element>;">Text 1 2 3 Foo</a> <a href="/">Link</a> 

Thanks.

EDIT (another example):

 <div myDirective="Text 1 2 3 Foo"> <ul> <li>Bar</li> </ul> </div> 

gives:

 <a class="tooltip" style="left:<the left pos of the original element>; top:<the top pos of the original element>;">Text 1 2 3 Foo</a> <div myDirective="Text 1 2 3 Foo"> <ul> <li>Bar</li> </ul> </div> 

Therefore, in essence, I want to insert a tooltip element in front of this element, but keep this element in the output and not replace it.

+4
source share
1 answer
 .directive('myDirective', function() { return { template: "<a class="tooltip" >{{txt}}</a><a href="/">Link</a>", restrict : 'A', scope: { txt : "@myDirective" }, replace: true, link: function(scope,elm,attrs) { } } }) 

Although I'm sure Angular requires one element to replace another. So if the above code should not work, use it (wrap it with a space):

 .directive('myDirective', function() { return { template: "<span><a class="tooltip" >{{txt}}</a><a href="/">Link</a></span>", restrict : 'A', scope: { txt : "@myDirective" }, replace: true, link: function(scope,elm,attrs) { } } }) 

Greetings, Henry

UPDATE : General method on request:

 .directive('myDirective', function() { return { template: '<span bind-html-unsafe="{{tmp}}"></span>', restrict : 'A', scope: { txt : "@myDirective" }, replace: true, link: function(scope,elm,attrs) { scope.tmp = '<'+attrs.tag+' class="tooltip" >{{txt}}</'+attrs.tag+'><a href="/">Link</a>' } } }) 

your html:

 <legend myDirective="A Text" tag="legend"></legend> 

I see that you are new to Angular, so pay attention to the new area created here. You can access parent vars with {{$ parent.var}} if you need to. But you should not. It is better to pass them as attributes if there are not so many of them.

FINAL UPDATE tryout @ http://plnkr.co/edit/JSOH0cGcYiJIWsVkB8cP
what you can do is use the $ compilation to execute a custom template.

 .directive('directive', function($compile) { return { restrict : 'A', scope: { txt : "@directive" }, replace: true, compile: function compile(elm, attrs, transclude) { var e = elm; e.removeAttr("directive"); elm.replaceWith('<span directive="'+attrs.directive+'"><a class="tooltip" href="">{{txt}}</a>'+e[0].outerHTML+'</span>'); elm.append(e); return { pre: function preLink(scope, iElement, iAttrs, controller) { }, post: function postLink(scope, elm, iAttrs, controller) { $compile(elm.contents())(scope); } } } } }); 

your HTML template:

 <div directive="{{text}}"> <ul><li>list element</li></ul> </div> 

Good luck. Greetings, Henry

+2
source

Source: https://habr.com/ru/post/1482541/


All Articles