我刚刚开始使用AngularJS,并想创建一个自定义模板指令来创建“就地”可编辑表。这个想法将是这样的:

    <tr ng-repeat="customer in model.customers">
        <ng-template ng-hide="customer === model.selectedCustomer"> <!-- display template-->
            <td>{{customer.name}}</td>
        </ng-template>
        <ng-template ng-show="customer === model.selectedCustomer"> <!-- edit template -->
            <td><input type="text" ng-model="customer.name"/></td>
        </ng-template>
    </tr>


然后还可以扩展它以指定templateUrl,例如<ng-template template-url="foo.html"></ng-template>

当我将ng-show指令应用于我的自定义指令时,它不起作用。这是我的指令的代码:

var demo = angular.module("demo", [])
.directive("ng-template", function() {
    return {
        restrict: "E",
        replace: true,
        transclude: true
    }
});


和HTML(http://jsfiddle.net/benfosterdev/ASXyy/):

<div ng-app="demo">
    <table>
        <tr ng-repeat="name in ['jane', 'john', 'frank']">
            <ng-template ng-show="name !== 'frank'">
                <td>{{name}}</td>
            </ng-template>
        </tr>
    </table>
</div>


此外,当我查看生成的HTML时,我的自定义指令甚至没有出现在表中:

<div ng-app="demo" class="ng-scope">
    <ng-template ng-show="name !== 'frank'" class="">
    </ng-template>
    <table>
        <tbody>
          ...
        </tbody>
    </table>
</div>


本质上,我试图避免编写这样的代码(在每个ng-show元素上设置<td>指令):

<table>
    <tr ng-repeat="customer in customers">
        <ng-template>
            <td ng-hide="isSelected">{{customer.name}}</td>
            <td ng-hide="isSelected">{{customer.age}}</td>
            <td ng-hide="isSelected"><button ng-click="edit(customer)"</td>
            <td ng-show="isSelected"><input type="text" ng-model="customer.name"/></td>
            <td ng-show="isSelected"><input type="text" ng-model="customer.age"/></td>
            <td ng-show="isSelected"><button ng-click="save(customer)"</td>
        </ng-template>
    </tr>
</table>

最佳答案

当我查看您的代码时,我发生了几件事。


ng-include提供与您提议的扩展ng-template非常相似的功能。如果您要基于基础模型的状态加载视图,那么我认为这是要走的路。
如果您不打算从单独的视图文件中加载模板,为什么不对td元素仅使用ng-show(或ng-if / ng-switch,在大多数情况下我更喜欢)?


这是一些使用ng-include的示例代码:

<table>
    <thead>
        <th>One</th>
        <th>Two</th>
        <th>Three</th>
        <th></th>
    </thead>
    <tbody>
        <tr ng-repeat="item in items" ng-include="getTemplate(item)"></tr>
    </tbody>
</table>


这是完整的JSFiddle:http://jsfiddle.net/qQR6j/2

09-30 16:05
查看更多