angularjs – ng-show不适用于自定义指令

前端之家收集整理的这篇文章主要介绍了angularjs – ng-show不适用于自定义指令前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我刚刚开始使用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>

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

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

猜你在找的Angularjs相关文章