Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular directive only works once

I have a simple Angular directive but it only renders once.

Successive calls to the template fail to render.

HTML:

<div ng-app="myApp">
    A. <ui-foo value="1" />
       B. <ui-foo value="2" />
       C. <ui-foo value="'fubar'" />
</div>

JavaScript:

angular.module('ui.directives', []);
angular.module('ui', [ 'ui.directives'
]).value('ui.config', {});

angular
    .module('ui.directives', [])
    .directive('uiFoo', 
        function() {
          return {
            restrict: 'E',
              scope:{
                  value:'='
              },
              template: '<h1>This is my directive #{{value}}</h1>'
          };
        }
  );
angular.module('myApp', ['ui.directives']);

I would expect to see

A. This is my directive #1
B. This is my directive #2
C. This is my directive #fubar

but I only see the first line.

See my JsFiddle for a quick repo

What am I doing wrong?

like image 581
fiat Avatar asked Feb 19 '26 14:02

fiat


2 Answers

You need to close those tags of ui-foo like this:

<div ng-app="myApp">
   A. <ui-foo value="1"></ui-foo>
   B. <ui-foo value="2"></ui-foo>
   C. <ui-foo value="'fubar'"></ui-foo>
</div>

Else, the first directive replaces the other two.

like image 173
David Losert Avatar answered Feb 23 '26 08:02

David Losert


The solution to fix this is that you should nest each ui-foo tag into each corresponding controller like as this:

<div ng-app="myApp">
    <div ng-controller="aController">
    A. <ui-foo value="1" />
    </div>
    <div ng-controller="bController">
       B. <ui-foo value="2" />
    </div>
    <div ng-controller="cController">
       C. <ui-foo value="fubar" />
    </div>
</div>

Hope this will help you!!

like image 38
Scott Phat Avatar answered Feb 23 '26 10:02

Scott Phat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!