【问题标题】:angular.js two directives, second one does not executeangular.js 两个指令,第二个不执行
【发布时间】:2023-03-22 01:15:02
【问题描述】:

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

鉴于此 HTML:

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

还有这个 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');
    }
  };
});

生成的 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>

控制台输出也验证了这一点,因为仅输出“主指令”文本。

那么如果我切换主次元素的顺序,secondary指令执行,primary指令不执行:

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

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

【问题讨论】:

  • 答案是嵌入。
  • Transclusion跟这个无关,是简单的HTML语法错误。
  • 在阅读了嵌入并在我的指令中使用它之后,它起作用并解决了问题。我不知道为什么。这在当时似乎也没有意义。无论如何,我还是开枪了。
  • Transclusion 似乎可以解决问题,因为它可能已将 secondary 元素附加到 primary 元素而不是兄弟姐妹。

标签: javascript html angularjs angularjs-directive


【解决方案1】:

div 不是 void elements,需要一个结束标签。

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

Example

【讨论】:

  • 我遇到了同样的问题,但在我将 更改为 后,它得到了解决,受到这个答案的启发。
猜你喜欢
  • 2018-08-28
  • 2010-12-15
  • 2015-05-17
  • 2018-07-17
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 2012-11-18
  • 2019-06-27
相关资源
最近更新 更多