角。两个指令,第二个指令不执行

时间:2021-05-05 12:09:13

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.

我有两个角度定义的指令。js模块。首先声明的HTML元素执行它的指令,但是使用其他指令的第二个HTML元素不执行它。

Given this HTML:

鉴于这种HTML:

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

and this angular.js code:

这角。js代码:

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:

生成的HTML只是“主”指令,而“辅助”指令不呈现:

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

这是为什么呢?我做错了什么?

1 个解决方案

#1


7  

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

div不是void元素,需要关闭标签。

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

Example

例子

#1


7  

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

div不是void元素,需要关闭标签。

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

Example

例子