4

我想基于对象数组填充表。这个数组不包含相同类型的对象,对于每一行我想要一个完全不同的样式和onclick函数,基本上是完全不同的行为。 例如,基于数据动态选择指令

var data=[ 
    { 
    type:'dir-b', 
    data: { ... } 
    }, 
    { 
    type:'dir-b', 
    data: { ... } 
    }, 
    { 
    type:'dir-c', 
    data: { ... } 
    } 
] 

对于DIRB我希望有一个模板,控制器和DIRC完全不同的功能和模板对象类型。

我找到的解决方案是创建3个指令。其中一个将运行,以确定其他两个指令中的一个要基于数据添加。

.directive("dirA", function($compile){ 
    return{ 
    restrict:'A', 
    priority:1000, 
    terminal:true, 
    link: function(scope, element, attribute){ 
     element.removeAttr("dir-a");//prevent endless loop 
     element.attr(attribute.type,""); 
     $compile(element)(scope); 
    } 
    } 
}) 
.directive("dirB", function($compile){ 
    return{ 
    restrict:'A', 
    replace:true, 
    link: function(scope, element, attribute){ 
     console.log("dirA"); 
    } 
    } 
}) 
.directive("dirC", function($compile){ 
    return{ 
    restrict:'A', 
    replace:true, 
    link: function(scope, element, attribute){ 
     console.log("dirC"); 
    } 
    } 
}); 

使用<tr dir-a type='{{d.type}}' ng-repeat='d in data'/>没有达到预期的效果。要么我给dirA优先级为0,它可以解析属性,但它重复的次数要比数组的大小多,或者我给它优先级为1000,它不能解析b.type并将其用作文字。 有没有人有这个解决方案?

回答

0

不知道这是最好的解决方案,但它是我找到的解决方案。由于

<table> 
    <tbody ng-repeat='d in data'> 
    <tr ng-if='d.type=="dir-b"' dir-b></tr> 
    <tr ng-if='d.type=="dir-c"' dir-c></tr> 
    </tbody> 
</table> 

这种方式NG-如果只有正确的行永远不会被显示,但问题是,有数据TBODY将被重复很多行。但直到有一个解决方案,这是我做到的。

0

您可以在这里使用ngSwitch

Plnkr

HTML

<div ng-repeat="(key, d) in data track by $index"> 
    <div class="tbody" ng-switch on="d.type"> 
    <div class="row" ng-switch-when="dir-b" dir-b>{{d}}</div> 
    <div class="row" ng-switch-when="dir-c" dir-c>{{d}}</div> 
    </div> 
</div> 

然后你只需定义dirBdirC指令。

虽然这不会显示为html表格,但您希望能够从此工作?