Question

So I'm trying to architect a simple Angular controller in a DRY fashion.

Basically a have two views. one is #/items the other is #/archiveditems

The pages are identical except that one page shows a list of archived items, the other shows current items. Also there is an <h2> that looks like <h2>{{itemState}} Items</h2>

I have an Angular Factory setup that returns an object that looks like {items: $resource(/api/items), archivedTtems: $resource(/api/archiveditems)}

Currently I have two separate controllers. The code is nearly identical in both. The only difference is the $scope.itemState and Api.archivedItems.query() vs Api.items.query()

Here's what the controller looks like in detail.

app.controller('currentItemsController', function($scope, Api){

    $scope.itemState = 'Current';

    $scope.items = Api.items.query(function () {

});

app.controller('archivedItemsController', function($scope, Api){

    $scope.itemState = 'Archived';

    $scope.items = Api.archivedItems.query(function () {

});

I fell that there is an elegant way I can merge these two controllers into one. Any help would be really appreciated!

Was it helpful?

Solution

you could have you route setup for /items/:type

and then in controller something like:

app.controller('itemsController', function($scope, Api, $routeParams){

    var isArchive = $routeParams.type == 'archived';
    $scope.itemState = isArchive ? 'Archived' : 'Current';
    $scope.items = Api[isArchive ? 'items' : 'archivedItems'].query(function () { ... });

});

so then when you call /items/archived - it would deal with your archived items .. also if your API returns the same thing back - why not just pass a flag "isArchived" instead of having a separate resource?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top