Angular Middleware
Laravel-like middleware for ngRoute & ui.router
Installation
-
Get it on your computer
- Bower
bower install --save angular-middleware
- NPM
npm install --save angular-middleware
- GitHub
git clone https://github.com/oldtimeguitarguy/angular-middleware
- Bower
-
Include
angular-middleware.min.js
in your app, whichever way you choose -
Include the module that works for you:
ui.router.middleware
ngRoute.middleware
Configuration & Examples
// An app with ui.router...var app = angular; // An app with ngRoute...var app = angular; /////////////////////////////////////////////////////////// Either way you go, the rest is essentially the same /////////////////////////////////////////////////////////// /** * First, you need to map your middleware functions. * This can be done cleanly with separate files * for each middleware function. You can do that * a number of different ways. I'll just show you * the basics. */app; /** * Now you're ready to use your middleware! * All you have to do is put them in your routes. * Each middleware is processed in the order you list them. * * The principle is the same for ui.router and ngRoute. * I'll show you both to make sure the dead horse is sufficiently beaten. */ /** ui.router */ app; /** ngRoute */ app;
$middlewareProvider
-
$middlewareProvider.map(<object>)
This is how you define and name your middleware. -
$middlewareProvider.bypassAll(<boolean>)
This gives you a way to easily bypass all middleware... as if it didn't exist! -
$middlewareProvider.global(<string|array>)
If you want to apply some middleware to all routes, you can easily do it here. The same rules apply to setting up middleware on routes, ie. you can use a string, a string with pipes, or an array of middleware names. NOTE: Anything defined here will be called before the route middleware is called.
Things you can do inside your middleware functions
If you don't know what I'm talking about, look at the example above
-
this.next()
must be called to resolve the middleware and either go to the next middleware or resolve the route -
this.redirectTo(dest [,params [,options]])
can be called to immediately redirect- dest (required): A path (ngRoute) or state name (ui.router) to redirect to
- params (optional): A params object to be used to populate query parameters (ngRoute) or
$stateParams
(ui.router) - options (optional): An object of transitionTo options (only used with ui.router)
-
this.route
is the destination route path -
this.params
is an object that contains the current route parameters