lkahtz
lkahtz

Reputation: 4796

In AngularJS, jquery append method seems not to be working in directives

I want to implement my own version of ng-repeat. But somehow I cannot get it working since the jquery append method seems not to be working.

script.js:

var app = angular.module("app", []);

app.directive("myRepeat", function() {
  return {
    restrict: 'E',
    compile: function(element, attrs) {
      var c = element.children()[0];
      console.log(c)
      for(var i=0; i<attrs.times; i++) {
        element.append(c);
      }
      return function(scope, element, attrs) {
        $(element).click(function() {
          console.log("hi");
        })
      }
    }
  }
})

index.html:

<body ng-app="app">
    <my-repeat times="5"><p>hello world</p></my-repeat>
</body>

Code in use at plnkr.co.

Upvotes: 1

Views: 479

Answers (1)

lkahtz
lkahtz

Reputation: 4796

I found the answer after reading a bit of code of jquery. Append will check and remove duplicate when appending DOM element. I packed c into a dom list and changed the append line in my for-loop into:

element.append(c.clone());

And the problem is gone.

Upvotes: 1

Related Questions