Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data from directive not displaying within ng-repeat

I have broken this problem down into it's simplest form. Basically I have a directive that, for the demo, doesn't yet really do anything. I have a div with the directive as an attribute. The values within the div, which come from an object array, are not displayed. If I remove the directive from the div, they are displayed OK. I am clearly missing something really obvious here as I have done this before without any problems.

Here's the Plunk: http://plnkr.co/edit/ZUXD4qW5hXvB7y9RG6sB?p=preview

Script:

app.controller('MainCtrl', function($scope) {

  $scope.tooltips = [{"id":1,"warn":true},{"id":2,"warn":false},{"id":3,"warn":true},{"id":4,"warn":true}];

});

app.directive("cmTooltip", function () {
    return {
        scope: {
            cmTooltip: "="
        }
    };
});

HTML

<div ng-repeat="tip in tooltips" class="titlecell" cm-tooltip="true">
    A div element: {{ tip.id }}
</div>
<br><br>

Just to prove it works without the directive:
<div ng-repeat="tip in tooltips" class="titlecell">
    A div element: {{ tip.id }}
</div>
like image 650
Craig Morgan Avatar asked Nov 23 '22 08:11

Craig Morgan


2 Answers

There is a hack to make it working in earlier versions of angular by making use of transclusion, like that:

app.directive("cmTooltip", function () {
    return {
        scope: {
           cmTooltip: "="
        },
        transclude:  true,
        template : '<div ng-transclude></div>'
    };
});

PLNKR

like image 195
artur grzesiak Avatar answered Dec 11 '22 00:12

artur grzesiak


As by Beyers' comment above and below, the behaviour the question is about no longer exists in at least 1.2.5

To be clearer; this has nothing to do with ng-repeat, you can remove it and there still will be no tip ( or tooltips ).

See this question on what the = and other configs mean and what it is doing for you.

Basically for your situation when you use = the scope of the directive will be used in the underlying elements, you no longer have your controller's scope. What this means for you is that there is no {{ tip.id }} or not even tip. Because the directive doesn't supply one.

Here's a plunker that demonstrates what you can do with it.

Basically all i did was

app.directive("cmTooltip", function () {
    return {
        scope: {
            cmTooltip: "="
        },
        link: function($scope){    // <<
          $scope.tip = { id: 1 };  // <<
        }                          // <<
    };
});

This creates the tip object on the scope so it has an id.

For your situation you would probably just not use = and look at this question for your other options depending on what you want.

like image 33
Philipp Gayret Avatar answered Dec 11 '22 02:12

Philipp Gayret