1

What is the best way to pass a param into a MEAN application while maintaining a pretty URL? I CANNOT use storage on the client for this. The following Express route will successfully bootstrap the param in the Angular application but the URL is ugly...

router.get('/:bid', function(req, res, next) {
    var bid = req.params.bid || '';
    res.render('index', { initData: { bid: bid } });
});

The parameterized URL:

http://localhost:4001/ABC123

Becomes:

http://localhost:4001/?bid=abc123#/login

I don't mind using a query string but I want the query string params to immediately vanish.

G. Deward
  • 1,542
  • 3
  • 17
  • 30

1 Answers1

1

(Fairly certain, from your other posts, you're using UI-Router. I'm going to assume this here.)

If you're using UI-Router, I would format the URL with the value as a parameter:

http://localhost:4001/#/login/abc123

As long as your State accounts for the parameter...

(function (module) {

    'use strict';

    var config = function ($stateProvider, $urlRouterProvider) {

        $urlRouterProvider.otherwise("/login");

        $stateProvider
            .state('login', { 
                url: '/login/:bid', 
                templateUrl: 'partials/login.html', 
                params: { 
                    bid: { squash: true, value: null } 
                } 
            });
    };

    module.config(config);

})(angular.module('your-app'));

You can then pull the value into your controller using $stateParams:

(function (module) {

    'use strict';

    var loginController = function ($stateParams) {

        var vm = this;

        vm.bid = $stateParams.bid || '';

    };

    module.controller('Login', loginController);

})(angular.module('your-app'));

And do with it what you will:

<div class="container" ng-controller="Login as login">
    <form class="form-signin">
        <h2 class="form-signin-heading">Please sign in: {{ login.bid }}</h2>
    </form>
</div>

The parameter will vanish from the URL the moment your user clicks on a link or navigates elsewhere.

Also, on a side note, this would also remove the dependency on Jade or injecting it via the view engine.

Fred Lackey
  • 2,351
  • 21
  • 34