Angular: Empty Fiddle
http://angularjs.org/
HTML
<script src="http://code.angularjs.org/1.2.1/angular-route.js"></script>
<script type="text/ng-template" id="static.tpl.html">
Static route
</script>
<script type="text/ng-template" id="dynamic.tpl.html">
Dynamic route
</script>
<script type="text/ng-template" id="default.tpl.html">
Default route
</script>
<div ng-controller="MyCtrl">
<ul>
<li><a href="#/static">static route</a>
</li>
<li><a href="#/dynamic">dynamic route</a>
</li>
</ul>
<button ng-click="defineRoute()">Define a route dynamically</button>
<hr>
<div ng-view></div>
</div>
JavaScript
var myApp = angular.module('myApp', ['ngRoute']);
myApp.controller('MyCtrl', function ($scope, $route) {
function addRoute(path, route) {
$route.routes[path] = angular.extend({
reloadOnSearch: true
},
route,
path && pathRegExp(path, route));
// create redirection for trailing slashes
if (path) {
var redirectPath = (path[path.length - 1] == '/') ? path.substr(0, path.length - 1) : path + '/';
$route.routes[redirectPath] = angular.extend({
redirectTo: path
},
pathRegExp(redirectPath, route));
}
return this;
};
function pathRegExp(path, opts) {
var insensitive = opts.caseInsensitiveMatch,
ret = {
originalPath: path,
regexp: path
},
keys = ret.keys = [];
path = path.replace(/([().])/g, '\\$1')
.replace(/(\/)?:(\w+)([\?\*])?/g, function (_, slash, key, option) {
var optional = option === '?' ? option : null;
var star = option === '*' ? option : null;
keys.push({
name: key,
optional: !! optional
});
slash = slash || '';
return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (star && '(.+?)' || '([^/]+)') + (optional || '') + ')' + (optional || '');
})
.replace(/([\/$\*])/g, '\\$1');
ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : '');
return ret;
}
$scope.defineRoute = function () {
addRoute('/dynamic', {
templateUrl: 'dynamic.tpl.html'
});
console.log($route);
};
});
myApp.config(function ($routeProvider) {
$routeProvider.when('/static', {
templateUrl: 'static.tpl.html'
});
$routeProvider.otherwise({
templateUrl: 'default.tpl.html'
});
});