codephobia
codephobia

Reputation: 1590

directive not working in ng-repeat

I have a simple directive that shows a tooltip of a larger image when you hover over a small image. It stopped working when I added it to an ng-repeat. The directive runs, it even creates the tooltip elements in the bottom of the body, but when I mouseover nothing shows.

The html:

<div ng-repeat="photo in photos track by $index" id="photo{{$index}}" data-tooltip-img="./photos/{{photo.large}}" big-photo>
  <a href="#">
    <img src="./photos/{{photo.small}}" alt="{{photo.name}}">
  </a>
</div>

The directive:

.directive('bigPhoto', function () {
    return {
        restrict: 'A',
        link: function (scope, el, attr) {
            var targetTag = "#"+attr['id'],
                xPos = (attr['tooltipPos'] && attr['tooltipPos'] === 'left') ? -304 : 20;
            angular.element(targetTag).wTooltip({
                delay: 0,
                offsetX: xPos,
                offsetY: 20,
                content: '<img src="'+attr['tooltipImg']+'" alt="'+attr['title']+'">',
                style: false
            });
        }
    };
})

jsFiddle: http://jsfiddle.net/codephobia/k6Ljzg7j/

Upvotes: 1

Views: 436

Answers (1)

Josep
Josep

Reputation: 13071

The problem is that you are accessing the element like this: angular.element(targetTag) and when your directive gets executed inside the ng-repeat, angular can't access the element like that (because it hasn't finished creating the element), however the link function is giving you that same element that it's being created, so you should use the one that it's given to you by the link function.

So, your directive should look like this:

app.directive('bigPhoto', function () {
    return {
        restrict: 'A',
        link: function (scope, el, attr) {
            var targetTag = "#"+attr['id'],
                xPos = (attr['tooltipPos'] && attr['tooltipPos'] === 'left') ? -304 : 20;
            el.wTooltip({
                delay: 0,
                offsetX: xPos,
                offsetY: 20,
                content: '<img src="'+attr['tooltipImg']+'" alt="">',
                style: false
            });
        }
    };
})

Working Example

Upvotes: 1

Related Questions