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表格,但您希望能夠從此工作?