Reputation: 5230
I have the following setup:
<h2>Current Items</h2>
<table ng-controller="ItemsController">
<tr ng-repeat="item in items">
<td>{{item.id}}</td>
</tr>
</table>
<h2>Past Items</h2>
<table ng-controller="ItemsController">
<tr ng-repeat="item in items">
<td>{{item.id}}</td>
</tr>
</table>
<script>
var app = angular.module('app');
app.factory('Items', ['$resource', function ($resource) {
return $resource('/api/items/:id/', {id: '@id'});
}]);
app.controller("ItemsController", function($scope, Items) {
$scope.items = Items.query({type: 'current'});
});
</script>
I cannot understand how to reuse the html table and the controller, but pass a different value for the type, so the Items service returns different results for the two tables.
I know I can create two controllers and inherit from a BaseItemsController, but it does not look right to me. Any better ideas?
Thanks!
Upvotes: 4
Views: 3250
Reputation: 20014
Based on your sample scenario my advise is that you need to use one controller and filter the item type: Current | Past in your repeater. Like this:
<div ng-controller="ItemsController">
<h2>Current Items</h2>
<table >
<tr ng-repeat="item in items | filter: /*CURRENT items*/">
<td>{{item.id}}</td>
</tr>
</table>
<h2>Past Items</h2>
<table >
<tr ng-repeat="item in items | filter: /*PAST items*/">
<td>{{item.id}}</td>
</tr>
</table>
</div>
This is with one single set of items.
Or you can have two sets of items in your controller like
$scope.pastItems = [];
$scope.currentItems=[];
Update 1:
If you use your controller in different pages you could set up a routing and with $routeparams
pass on a different initialization.
Upvotes: 3
Reputation: 5230
Here is my solution:
<h2>Current Items</h2>
<div ng-controller="ItemsController">
<div ng-include="'items.html'" onload="init('current')"></div>
</div>
<h2>Past Items</h2>
<div ng-controller="ItemsController">
<div ng-include="'items.html'" onload="init('past')"></div>
</div>
<script type="text/ng-template" id="items.html">
<table ng-controller="ItemsController">
<tr ng-repeat="item in items">
<td>{{item.id}}</td>
</tr>
</table>
</script>
<script>
var app = angular.module('app');
app.factory('Items', ['$resource', function ($resource) {
return $resource('/api/items/:id/', {id: '@id'});
}]);
app.controller("ItemsController", function($scope, Items) {
$scope.items = [];
$scope.init = function (type) {
$scope.items = Items.query({type: type});
};
});
</script>
Upvotes: 2