AngularJS-如何禁用从URL的访问 [英] AngularJS - How to disable access from URL
问题描述
我正在使用路线:
App.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/home', {
templateUrl: 'orders/list',
controller: OrderController
});
$routeProvider.when('/editOrder', {
templateUrl: 'addOrder/editOrder',
controller: ActionController
});
$routeProvider.otherwise({redirectTo: '/home'});
我只想单击按钮才能导航到编辑页面,但是此定义也允许通过浏览器通过url访问.是否可以禁用通过url的访问?
I want to navigate to the edit page only when a button is clicked, but this definition allows access via url from browser also. Is it possible to disable access via url ?
推荐答案
根据某些条件/权限,您可以使用 $ routeChangeStart
事件在要更改的路线和否决导航上实施自定义逻辑.在以下示例中,仅当您授予权限时,您才可以导航到/edit
路由,您可以使用 PermissionsService
服务来授予或撤消该权限.在以下示例中,您可以尝试通过直接链接导航,并看到您已重定向到默认路由,并且当您单击编辑"按钮时,您将重定向到相关路由.另外,如果您使用的是/edit
路线,并使浏览器来回移动,您会注意到您无法返回/edit
路线.
You can use $routeChangeStart
event to implement custom logic on route to be changed and veto navigation depending on some condition/permission. In the following example you can navigate to /edit
route only if you have granted permissions, which you can grant or revoke using PermissionsService
service. In the following example you can try to navigate via direct link and see that you are redirected to default route, and when you click Edit button you are redirected to the relevant route. Also, if you are on /edit
route and make browser back and forward, you can notice that you can't go back to /edit
route.
HTML
<a href="#/home">Home</a>
<a href="#/edit">Edit</a>
<div ng-view></div>
<button ng-click="edit()">Edit</button>
JavaScript
angular.module('app', ['ngRoute']).
config(['$routeProvider', function($routeProvider){
$routeProvider.when('/home', {
templateUrl: 'list.html',
controller: 'OrderController'
});
$routeProvider.when('/edit', {
templateUrl: 'edit.html',
controller: 'ActionController'
});
$routeProvider.otherwise({redirectTo: '/home'});
}]).
run(['$rootScope', '$location', 'PermissionsService', function($rootScope, $location, PermissionsService) {
$rootScope.edit = function() {
PermissionsService.setPermission('edit', true);
$location.path('/edit');
};
$rootScope.$on("$routeChangeStart", function(event, next, current) {
if (next.templateUrl === "edit.html") {
if(!PermissionsService.getPermission('edit')) {
$location.path('/');
}
PermissionsService.setPermission('edit', false);
}
});
}]).
service('PermissionsService', [function() {
var permissions = {
edit: false
};
this.setPermission = function(permission, value) {
permissions[permission] = value;
}
this.getPermission = function(permission) {
return permissions[permission] || false;
}
}]).
controller('OrderController', [function() {}]).
controller('ActionController', [function() {}]);
实时示例此处.
Live example here.
这篇关于AngularJS-如何禁用从URL的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!