0

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!

1 Answer 1

1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah I thought about passing a flag or even doing items: $resource('/api/items/:state') But writing Api.items.query({state: 'archived'}) seemed the same as writing Api.archivedItems.query() If there was more than one state then passing a flag seemed to make more sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.