How to work with traffic control in AngularJS applications

I am interested in finding an intelligent way to manage paths (as in URLs) for various parts of the application.

If you have HTML ( hrefattributes), controllers and services ( $location.path()calls), it is very messy to change the url from say / login to / auth. You need to go through all your JS and HTML files that are looking for links to them.

How to do it? I think of the paths object as angular.constantbeing introduced into the scope of HTML files and referenced as JS objects in controllers and services in order to have one place to store them.

Would this be a good way to do this? Is there a better way?

Thanks.

+4
source share
2 answers

I ran into the same problem that you are describing. I had hardcoded URLs in my application, and changing something was a nightmare. So I decided to come up with a good solution. And that’s what I finally decided. It may not be perfect, but so far I have not had any problems. PS. My application is huge, so there are many tracking URLs.

.constant('RoutePaths', {
    login: {
        login: '/login',
        eula: '/login/eula',
        noSubscription: '/no-subscription',
        myAccount: '/my-account',
        createAccount: '/my-account/create',
        createAccountFromXID: '/my-account/update',
        ...
        // more routes here
    },
    conreg: {
        compInfo: '/bronze/companyInfo',
        serviceArea: '/bronze/serviceArea',
        licenses: '/bronze/licenses',
        insuranceBonds: '/bronze/insuranceAndBonds',
        certifiedReviews: '/silver/certifiedReviews',
        certifications: '/silver/certifications',
        yearsAndBBB: '/silver/yearsAndBBB',
        ...
        // more routes here
    },
    ....
    // more objects here
}

Since I declared this object RoutePathsas constant, now I can use it in my application configin combination with the built-in $routeProvideras such:

app.config(['$routeProvider','RoutePaths', function($routeProvider, RoutePaths){
    var login = RoutePaths.login;
    $routeProvider
        .when(login.login, {templateUrl: '../partials/login/login.html', controller: 'LoginCtrl'})
        .when(login.eula, {templateUrl: '../partials/login/eula.html', controller: 'EulaCtrl'})
        .when(login.myAccount, {templateUrl: '../partials/login/account.html', controller: 'AccountCtrl'})
        ...
        // more routes declared here
}]);

And you can introduce the same dependency RoutePathsin any controllers, services, factories, filters, etc. that you need:

.controller('LoginCtrl', ['$scope','RoutePaths', function($scope, RoutePaths){
    $scope.paths = RoutePaths.login;
    ...
}]);

And in your views, you can get attached to these paths using:

<a ng-href="{{paths.myAccount}}">My Account</a>

, , RoutePaths, . . - ?

+2
+2

All Articles