Search code examples
angularjsangularjs-directivecoffeescriptqtip2

ngRepeat with $scope.$apply creates duplicates in directive


I have a directive that puts dynamic data into a qTip via a template. It does so by fetching the template and using $compile on it (excuse the coffeescript):

$http.get scope.qtipTemplate, cache: $templateCache
.then (html) ->
  clone = $compile html.data
  generateQtip text: ->
    scope.$apply ->
      clone scope

The generateQtip simply creates a new qTip on the directive element and puts the first argument as the content property on the options object.

What happens though is, every time I open the qTip, the ngRepeat in the template produces duplicate lists, even with limitTo as a filter. Example code:

<ul>
    <li ng-repeat="person in object.people | limitTo:3 track by $index">{{person.name}}</li>
</ul>

Produces the following the first time I open the qTip:

  • John Doe
  • Jane Doe
  • Johnny Dowy

And this on the second time:

  • John Doe
  • Jane Doe
  • Johnny Dowy
  • John Doe
  • Jane Doe
  • Johnny Dowy

And this on the third time:

  • John Doe
  • Jane Doe
  • Johnny Dowy
  • John Doe
  • Jane Doe
  • Johnny Dowy
  • John Doe
  • Jane Doe
  • Johnny Dowy

And so on, and so on.

Why does this happen? Any ideas? Here's my full directive code in this link.


Solution

  • Not sure why, but I simply had to move the $compile further inside.

    $http.get scope.qtipTemplate, cache: $templateCache
    .then (html) ->
      generateQtip text: ->
        scope.$apply ->
          $compile(html.data)(scope)