fiat
fiat

Reputation: 15981

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?

Upvotes: 2

Views: 2265

Answers (2)

Scott Phat
Scott Phat

Reputation: 71

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!!

Upvotes: 1

David Losert
David Losert

Reputation: 4802

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.

Upvotes: 10

Related Questions