Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning elements (bindings and all) in AngularJs

Is there a way to clone an element in AngularJS, with its bindings intact?

I am trying to create an image pre-loader for a gallery. The image loads off screen and is then moved into one of three columns depending on its size. So it actually does need to be moved with JavaScript since I don't know until it is loaded which container it is supposed to go into.

So assume I have something like:

<img ng-src="/some/{{image}}" ng-click="doStuff()" />

I want the clone to be identical to this, with the ng-click binding intact. The problem I am encountering is that if I clone the element using element.clone().appendTo(someOtherElement) then the ng-click binding is lost along the way. When the element is inserted in the DOM Angular does not realize that it needs to create new bindings.

I have been experimenting with $compile, but I can't figure out how to clone an existing element using it without manually copying all attributes.

The cloning is done by a directive and I am only using Angular (no jQuery save what is included in Angular).

like image 538
Erik Honn Avatar asked Nov 11 '13 11:11

Erik Honn


1 Answers

You should do three separate ng-repeats:

<div ng-controller="myController">
     <div class="col1">
          <img ng-src="/some/{{image.src}}" ng-click="doStuff()" ng-repeat="image in imagesForColOne" />
     </div>

     <div class="col2">
          <img ng-src="/some/{{image.src}}" ng-click="doStuff()" ng-repeat="image in imagesForColTwo" />
     </div>

     <div class="col3">
          <img ng-src="/some/{{image.src}}" ng-click="doStuff()" ng-repeat="image in imagesForColThree" />
     </div>

</div>

In your controller you should load your images asynchronously and then push them into one of the three arrays depending on its size.

like image 168
Jeremythuff Avatar answered Sep 23 '22 21:09

Jeremythuff