fodma1 fodma1 - 26 days ago 13
AngularJS Question

Possible Angular attribute directive bug?

I'm trying to create an Angular directive which is just an HTML attribute (

my-directive
). This directive uses some input attributes (
text
,
length
).

<li my-directive text="first" length="6"></li>


Everything works nicely when I use it just once. But I'd like to use it multiple times, for list items:

<ul>
<li my-directive text="first" length="elements[0].len"></li>
<li my-directive text="second" length="elements[1].len"></li>
<li my-directive text="third" length="elements[2].len"></li>
<li my-directive text="fourth" length="elements[3].len"></li>
</ul>


This is when I experience a weird behaviour: Each list item displays the last item's attributes. I checked it, and the directive controllers receive the different values. Still, only the last one is displayed.

I'm pretty sure someone else bumped into this before, but I couldn't find anything related.

Plunkr here

UPDATE:

It looks like this issue can be solved using
ng-repeat
, but I'd rather not use that. And still it looks like a bug to me.

Answer

use isolated scope for directive will solve the problem

http://plnkr.co/edit/pwfbShFYLPMHlSLf48ng?p=preview

.directive('myDirective', function () {
    return {
      restrict: 'A',
      bindToController: {
        // text: '@text',
        length: '='
      },
      scope: {},
      controller: function() {
        var ctrl = this;
        return ctrl;
      },
      controllerAs: 'ctrl',
      template: '{{ ctrl.text }} - {{ ctrl.length }}'
    }
  });
Comments