简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM