Search code examples
angularjsrestangular-resourceangular-routing

How to reduce code redundancy when defining routes in AngularJS


I am currently coding a Rest API and a client in AngularJS. I am using the Angular modules

  • angular-resource (ngResource)
  • angular-route (ngRoute)

This is how my routing configuration looks like:

$routeProvider
.when('/facility', {
    templateUrl: pathTemplate + 'Facility/index.html',
    controller: 'FacilityIndexController',
    resolve: {
        Facilities: ['Facility', function(Facility) {
            return Facility.query();
        }]
    }
})
.when('/facility/show/:id', {
    templateUrl: pathTemplate + 'Facility/show.html',
    controller: 'FacilityShowController',
    resolve: {
        Facility: ['Facility', '$route', function(Facility, $route) {
            return Facility.get({id: $route.current.params.id});
        }]
    }
})
.when('/facility/edit/:id', {
    templateUrl: pathTemplate + 'Facility/edit.html',
    controller: 'FacilityEditController',
    resolve: {
        Facility: ['Facility', '$route', function(Facility, $route) {
            return Facility.get({id: $route.current.params.id});
        }]
    }
})

And this is just one entity. Additionally I needed to define for each "action" one controller. I put them all together for this single entity:

'use strict';
angular.module('app')
.controller('FacilityIndexController', ['$scope', 'Facilities', function($scope, Facilities) {
    $scope.facilities = Facilities;
}])
.controller('FacilityShowController', ['$scope', 'Facility', function($scope, Facility) {
    $scope.facility = Facility;
}])
.controller('FacilityCreateController', ['$scope', 'Facility', function($scope, Facility) {
    $scope.facility = new Facility();
    // $scope.facility.$save();
}])
.controller('FacilityEditController', ['$scope', 'Facility', function($scope, Facility) {
    $scope.facility = Facility;

    $scope.update = function() {
        var id = $scope.facility.id;
        $scope.facility.$update({id: id}).then(function(response){
            $scope.goTo('facility/show/' + id);
        });
    };
}]);

I think working with $resource is super cool, because everything works automatically... well, just the redundancy is very high.

Do you have some best practices here? Thanks in advance.


Solution

  • You can always take out the logic of Facility.get({id: $route.current.params.id}); in some service/factory but that would IMHO be just over-engineering. Apart from this, I don't see much redundancy, since most of that code is just declaration of things.