2013-06-24 64 views
4

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

鉴于这种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> 

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

然后,如果我切换的初级和次级元件的顺序,执行次级指令和初级指令不:

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

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

+0

答案是transclusion。 – kindohm

+0

Transclusion与此无关,它是一个简单的HTML语法错误。 – rtcherry

+1

阅读了关于跨语言的知识并在我的指示中使用它之后,它能够解决问题。我不知道为什么。当时似乎也没有意义。无论如何我都跳过了枪。 – kindohm

回答

7

div的不是void elements并且需要结束标记。

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

Example

+7

我遇到了同样的问题,但在将更改为之后,由此答案启发,它解决了。 – newman

相关问题