angular.js有两个指令,第二个指令不执行

kin*_*ohm 4 html javascript angularjs angularjs-directive

我在angular.js模块中定义了两个指令.首先声明的HTML元素执行其指令,但使用other指令的第二个HTML元素不执行它.

鉴于此HTML:

<div ng-app="myApp">
  <div ng-controller="PlayersCtrl">
    <div primary text="{{primaryText}}"/>
    <div secondary text="{{secondaryText}}"/>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

和这个angular.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');
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

生成的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>
Run Code Online (Sandbox Code Playgroud)

控制台输出也会验证这一点,因为只输出"主要指令"文本.

然后,如果我切换主要和次要元素的顺序,则执行辅助指令并且指令不是:

<!-- 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>
Run Code Online (Sandbox Code Playgroud)

为什么是这样?我究竟做错了什么?

rtc*_*rry 7

div不是空元素,需要一个结束标记.

<div ng-app="myApp">
  <div ng-controller="PlayersCtrl">
    <div primary text="{{primaryText}}"></div>
    <div secondary text="{{secondaryText}}"></div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 我遇到了同样的问题,但是在我将<my-directive />更改为<my-directive> </ my-directive>后,它得到了解决,受到了这个答案的启发. (7认同)