Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular.js two directives, second one does not execute

I have two directives defined in an angular.js module. The HTML element that is declared first executes its directive, but the second HTML element that uses the other directive does not execute it.

Given this HTML:

<div ng-app="myApp">
  <div ng-controller="PlayersCtrl">
    <div primary text="{{primaryText}}"/>
    <div secondary text="{{secondaryText}}"/>
  </div>
</div>

and this angular.js code:

var myApp = angular.module('myApp', []);

function PlayersCtrl($scope) {
    $scope.primaryText = "Players";
    $scope.secondaryText = "the best player list";
}

myApp.directive('primary', function(){
  return {
    scope: {
      text: '@'
    },
    template: '<h1>{{text}}</h1>',
    link: function(scope, element, attrs){
      console.log('primary directive');
    }
  };
});

myApp.directive('secondary', function(){
  return {
    scope: {
      text: '@'
    },
    template: '<h3>{{text}}</h3>',
    link: function(scope, element, attrs){
      console.log('secondary directive');
    }
  };
});

The resulting HTML is only the "primary" directive, and the "secondary" directive does not render:

<div ng-app="myApp" class="ng-scope">
  <div ng-controller="PlayersCtrl" class="ng-scope">
    <div primary="" text="Players" class="ng-isolate-scope ng-scope">
      <h1 class="ng-binding">Players</h1>
    </div>
  </div>
</div>

The console output verifies this as well, as only the "primary directive" text is output.

Then if I switch the order of the primary and secondary elements, the secondary directive is executed and the primary directive is not:

<!-- reversed elements -->
<div secondary text="{{secondaryText}}"/>
<div primary text="{{primaryText}}"/>

<!-- renders this HTML (secondary, no primary) -->
<div ng-app="myApp" class="ng-scope">
  <div ng-controller="PlayersCtrl" class="ng-scope">
    <div secondary="" text="the best player list" class="ng-isolate-scope ng-scope">
      <h3 class="ng-binding">the best player list</h3>
    </div>
  </div>
</div>

Why is this? What am I doing wrong?

like image 312
kindohm Avatar asked Mar 24 '23 10:03

kindohm


1 Answers

div's are not void elements and require a closing tag.

<div ng-app="myApp">
  <div ng-controller="PlayersCtrl">
    <div primary text="{{primaryText}}"></div>
    <div secondary text="{{secondaryText}}"></div>
  </div>
</div>

Example

like image 158
rtcherry Avatar answered Apr 01 '23 07:04

rtcherry