2014-10-17 30 views
1

我發現在angularJS中顯示幾個表時,我違反了「不要重複自己」的口頭禪。angularJS ng-repeat迭代器字符串重用

這裏我們有一個展示的第一個名字或基於相同的NG-重複的姓氏兩個模板簡單(可笑)情況:

firstname.html:

<table> 
    <tr ng-repeat="person in people | filter: filterText | orderBy: sortField"> 
    <td>{{ person.first }}</td> 
    </tr> 
</table> 

姓氏html的:

<table> 
    <tr ng-repeat="person in people | filter: filterText | orderBy: sortField"> 
    <td>{{ person.last }}</td> 
    </tr> 
</table> 

現在,如果我想改變迭代器的表情,我必須這樣做兩次,一次在每個模板。看來,NG-包括不支持transclusion,或者我會做這樣的事情:

iterator.html:

<tr ng-repeat="person in people | filter: filterText | orderBy: sortField"> 
    <ng-transclude></ng-transclude> 

firstname.html:

<table> 
    <ng-include src="iterator.html"> 
    <td>{{ person.first }}</td> 
    </tr> 
</table> 

真正的表比較複雜,所以它不像這個例子那麼微不足道。我可以想象爲此創建一個指令,但它是爲我的應用程序的單個頁面,所以它似乎矯枉過正。此外,ng-repeat =「getFilteredAndSortedPeople()中的人」是一個選項,但是在每個摘要上調用該函數的性能很差。

有沒有人有最好的方法來完成這個建議?

回答

1

你可以重構代碼到一個指令:

app.directive('tableRow', function() { // app is the name of your angular module 
    return { 
     scope: { 
      items: '=', 
      field: '@', 
      filterText: '=', 
      sortField: '=' 
     }, 
     template: '<tr ng-repeat="item in items | filter: filterText | orderBy: sortField"><td>{{ item[field] }}</td></tr>' 
    }; 
}); 

然後使用像這樣:

<table> 
    <table-row items="people" field="first" filter="filterText1" order-by="sortField1"> 
    <table-row items="people" field="last" filter="filterText1" order-by="sortField1"> 
</table> 

因爲代碼是比較複雜的,我會建議更換提取模板HTML文件並使用templateUrl道具進入指令:

return { 
    scope: { 
     items: '=', 
     field: '@', 
     filterText: '=', 
     sortField: '=' 
    }, 
    templateUrl: 'url_to_new.html' 
}; 
0

Nicolás'answer works,但仍然在模板中留下很多重複。我結束了一個解決方案,在模板中留下很少的重複。簡而言之:

app.directive("myRepeat", function($compile) { 
    return { 
    terminal:true, 
    priority:1001, 
    link: { 
     pre: function(scope, el, attrs) { 
     el.removeAttr('my-repeat'); 
     el.attr('ng-repeat', scope.$eval(attrs.myRepeat)); 
     $compile(el)(scope); 
     } 
    } 
    }; 
}); 

在控制器:

$scope.iteratorString = "item in items | filter: foo | orderBy: bar"; 

在模板:

<tr myRepeat="iteratorString">...</tr>