Reputation: 583
Is there a way to create a function in html view. Because I have data and I used ng-repeat to diplay them in my html view. I used ng-if to display the first 15 data in the first table and the second 15 data in the second table and so on... . My concern now is I am creating a table three times and I think it's repetitive code. The 3 tables have the same code except I only changed the ng-if condition. I want a shorter code to make it reusable. Is there a way for it? Thanks.
My fiddle is here: https://jsfiddle.net/DharkRoses/kpw43k95/
sample of my code is:
<table border=1>
<tr ng-repeat="user in users" ng-if = "$index <= 14">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.stat}}</td>
</tr>
</table>
Upvotes: 1
Views: 213
Reputation: 365
The quick and dirty way :
<table border=1 ng-repeat="col in [0,1,2]">
<tr ng-repeat="user in users" ng-if = "$index >= col*15 && $index < (col+1)*15">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.stat}}</td>
</tr>
</table>
https://jsfiddle.net/ocuznpov/
But it will not adapt to the length of the array if you get over 15*3 items
Upvotes: 2
Reputation: 15715
You can create a directive for that, see https://jsfiddle.net/kpw43k95/1/
here I have created a directive name uiFoo
, which contains the template for the table,
Directive:
app.directive('uiFoo',
function() {
return {
restrict: 'EAC',
template:'<td>{{user.id}}</td><td>{{user.name}}</td><td>{{user.stat}}</td>',
link: function($scope, element, attrs, controller) {
}
};
}
);
Html:
<div ng-app="myApp" ng-controller="check">
<div class = "container">
<table border=1>
<tr ng-repeat="user in users" ui-foo ng-if = "$index <= 14">
</tr>
</table>
<table border=1 class>
<tr ng-repeat="user in users" ui-foo ng-if = "$index > 14 && $index <=29">
</tr>
</table>
<table border=1>
<tr ng-repeat="user in users" ui-foo ng-if = "$index > 29">
</tr>
</table>
</div>
</div>
link the template html in your directive, and you are done! its reusable.
Upvotes: 0