2013-06-24 19 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

相關問題