Angular.js two directives, the second is not executed

I have two directives defined in the angular.js module. The HTML element declared first executes its directive, but the second HTML element, which uses a different 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 just the "primary" directive, and the "secondary" directive does not display:

 <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 output to the console also checks this, since only the text of the "primary directive" is displayed.

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?

+4
source share
1 answer

div 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

+7
source

Source: https://habr.com/ru/post/1487956/


All Articles