指令不在ng-repeat内呈现

时间:2016-05-18 19:53:20

标签: angularjs

指令test-dir无法呈现

extension NSRange {
    func toTextRange(textInput textInput:UITextInput) -> UITextRange? {
        if let rangeStart = textInput.positionFromPosition(textInput.beginningOfDocument, offset: location),
            rangeEnd = textInput.positionFromPosition(rangeStart, offset: length) {
            return textInput.textRangeFromPosition(rangeStart, toPosition: rangeEnd)
        }
        return nil
    }
}

用作属性时会渲染。不知道为什么它不会作为一个元素工作。

PLNKR:http://plnkr.co/edit/fraBDzt9kjZlUIuV1fDf?p=preview

2 个答案:

答案 0 :(得分:1)

首先,您需要将replace: true添加到testDir指令。

否则你在<div>内会有一个<tr>,这就是为什么当用作元素时不会呈现该指令。

但是,即使使用replace: true,您也会遇到known bug

Error: Template must have exactly one root element. was: <td>{{data}}</td>

最好将指令用作attribute

答案 1 :(得分:0)

只需使用ng-repeat和<test-dir ng-repeat="row in person.entries" data="row"></test-dir>

等指令

所以您的代码将

<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <script>document.write("<base href=\"" + document.location + "\" />");</script>
  <link rel="stylesheet" href="style.css">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.js"></script>
<script>
     var app = angular.module('plunker', []);
app.directive("testDir", function(){
    return {
        restrict: 'EA',
        scope: {
          data: '='
        },
        template: "<td>{{data}}</td>"
    };
});


app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.data = [
    {
      name: 'cars',
      entries: [
        {model: 'fiat', speed: 100 },
        {model: 'tesla', speed: 200 },
        ]
    },
    {
      name: 'trucks',
      entries: [
        {model: 'volvo', speed: 50 },
        {model: 'merc', speed: 75 },
        ]
    }
    ];

});
</script>
  <script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
  <ul>
     <li ng-repeat="person in data">
        <table>
          <thead>{{person.name}}</thead>
          <tbody>
           <tr >
             <test-dir ng-repeat="row in person.entries" data="row"></test-dir>
           </tr>
          </tbody>
        </table>
    </li>
  </ul>




</body>
</html>