2014-01-30 42 views
3

我遇到了一些來自ngRepeat指令的意外行爲。這裏是一個非常簡單的例子:爲什麼ngRepeat不包含ngInclude或directive之後的元素?

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="app"> 
<body ng-controller="ctrl"> 

    <h1>test with directive</h1> 
    <ul> 
     <li ng-repeat="item in list">   
      <div> 
       <test /> 
       <p>And another thing...</p> 
      </div> 
     </li> 
    </ul> 

    <h1>test with ng-include</h1> 
    <ul> 
     <li ng-repeat="item in list"> 
      <ng-include src="'test.html'" /> 
      <p>And another thing...</p> 
     </li> 
    </ul> 

    <h1>test with inline switch</h1> 
    <ul> 
     <li ng-repeat="item in list"> 
      Hello, 
      <div ng-switch="item.name"> 
       <div ng-switch-when="John">Johnny-boy</div> 
       <div ng-switch-when="Mary">Mary-doll</div> 
      </div> 
      ! 
      <p>And another thing...</p> 
     </li> 
    </ul> 

    <script src="angular.js" type="text/javascript"></script> 
    <script type="text/javascript"> 

     var app = angular.module("app", []); 

     app.directive("test", function() { 
      return { 
       restrict: "E", 
       scope: false, 
       templateUrl: function() { return "test.html" }, 
       replace: true, 
       link: function (scope, elem, attrs) { 
        console.log(scope, elem, attrs); 
       } 
      } 
     }); 

     app.controller("ctrl", function ($scope) { 
      $scope.list = [ { name: "John" }, { name: "Mary" } ]; 
     }); 

    </script> 
</body> 
</html> 

的test.html的文件是這樣的:

<div> 
    Hello, 
    <div ng-switch="item.name"> 
     <div ng-switch-when="John">Johnny-boy</div> 
     <div ng-switch-when="Mary">Mary-doll</div> 
    </div> 
    ! 
    <hr/> 
</div> 

,我期望從每個測試輸出相同(使用指令,NG-包括或內嵌HTML) 。然而,對於指令和ng-include測試,ng-repeat中的最後一個p元素缺失。換句話說,這條線......

<p>And another thing...</p> 

..不會讓它進入DOM。我是否錯過了ng-repeat的行爲?或者它是一個錯誤?

回答

4

它看起來像使用斜槓關閉開始標記內的標記導致了問題。添加一個明確的結束標籤將解決問題。

在你的指令,例如:<test />應該<test></test>

在您的NG-包括例如:<ng-include src="'test.html'" />應該<ng-include src="'test.html'"></ng-include>


看到這個simplified fiddle再現問題沒有NG重複和this fixed fiddle與結束標籤。

+0

謝謝!一切看起來都像預期的那樣具有明確的結束標籤。簡直不敢相信我會這麼做。 – rom99

+0

@Gloopy感謝您指出這一點,rom99爲什麼你不把它標記爲正確答案? – gae123

相關問題