Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate attributes when using directive compile with transclude

Tags:

angularjs

JsFiddle of the issue: http://jsfiddle.net/UYf7U/

When using the angularJs transclude within a directives compile, it will duplicate any attribute properties. I.e.

<a class="myClass">my link</a>

Will become

<a class="myClass myClass">my link</a>

Similarly, when using an ngClick

<a ng-click="myFunction()"> my link</a>

Will become

<a ng-click="myFunction() myFunction()"> my link</a>

The fiddle demonstrates this, and unfortunately it crashes. It's a stripped down version of what I'm trying to implement.

Is there a way around this? I've posted the issue to github to: https://github.com/angular/angular.js/issues/2576

When clicking on Hello the word "clicked" should appear in an alert.

like image 720
Mathew Berg Avatar asked May 03 '13 16:05

Mathew Berg


2 Answers

This happens because myDirective is being initialized twice - first as part of your markup:

 <div class="transcludeMe">
     <div data-transclude-this="here">
         <div class="myDirective"></div>
     </div>
 </div>

Second in the transcludeMe directive - since you do this in the compile stage of the directive initialization:

transcludeHere[0].innerHTML = clone[x].innerHTML

Since you use replace:true all attributes of the original element will get copied to the template element. If you remove this your example works, but you still be aware that myDirective is getting initialized two times: http://jsfiddle.net/tkzgG/

like image 188
joakimbl Avatar answered Sep 19 '22 03:09

joakimbl


How important is it to you to specify the directive name as a class? This issue does not occur when the directives are used as elements directly.

See http://jsfiddle.net/smmccrohan/cfP3U/

Like thus, plus replacing the restrict: 'C' with restrict: 'E' in the directive definitions (and making some case changes to avoid an issue there):

<div ng-app="app">
 <div ng-controller="ParentCtrl">
     <transcludeme>
         <div data-transclude-this="here">
             <mydirective />
         </div>
     </transcludeme>
 </div>
</div>
like image 45
S McCrohan Avatar answered Sep 20 '22 03:09

S McCrohan