我会创建一个类似这样的服务:
app.factory('routeAuths', [ function() {
var routeAuths = [{
path : '/template1.*',
access : 'restricted'
}];
return {
get : function(path) {
var routeAuth;
for ( var i = 0; i < routeAuths.length; i += 1) {
routeAuth = routeAuths[i];
var routeAuthRegex = new RegExp(routeAuth.path);
if (routeAuthRegex.test(path)) {
if (routeAuth.access === 'restricted') {
return {
access : 'restricted',
path : path
};
}
}
}
return {
access : 'allowed',
path : path
};
}
};
} ]);
还有在主/根控制器中监听$locationChangeStart
事件:
app.controller('AppController', ['$scope', '$route', '$routeParams', '$location', 'routeAuths',
function(scope, route, routeParams, location, routeAuths) {
scope.route = route;
scope.routeParams = routeParams;
scope.location = location;
scope.routeAuth = {
};
scope.$on('$locationChangeStart', function(event, newVal, oldVal) {
var routeAuth = routeAuths.get(location.path());
if (routeAuth.access === 'restricted') {
if (scope.routeAuth.allowed) {
event.preventDefault();
}
else {
location.url('/main');
}
scope.routeAuth.restricted = routeAuth;
}
else {
scope.routeAuth.allowed = routeAuth;
scope.routeAuth.restricted = undefined;
}
});
}]);
示例:
参考资料:
更新:
为了完全防止html模板访问,最好也在服务器上进行处理。因为如果您从服务器的静态文件夹中提供html,则用户可以直接访问该文件,例如:root_url/templates/template1.html,从而规避angular检查器。