i want create a route for angularJs which will be accessible only from application code and links. The main idea is to prevent the user to access the page after directly typing route url in browser's location bar.
For route configuration i use "ngRoute" module's $routeProvider.
I can't find an answer for this question. Is the thing i need possible?
Thanks in advance.
You can listen $locationChangeStart event. In your routes you can set a parameter (I've called it "restricted" but you could call it whatever you want) like this:
app.config(function($routeProvider) {
$routeProvider
.when('/', {
controller: 'MainCtrl',
template: 'Allowed from anywhere.<br>Go to main page',
restricted: false
})
.when('/main', {
controller: 'MainCtrl',
template: 'Allowed from anywhere.<br>Go to restricted page',
restricted: false
}).when('/restr', {
controller: 'RestrictedPageCtrl',
template: 'Allowed only from main',
restricted: '/main'
});
});
If it's false, that means there's no restriction, if it's set to a path, then the route is only accessible from that path. And you can check it with this:
app.run(function($rootScope, $location, $route) {
$rootScope.$on('$locationChangeStart', function(event, next, current) {
var nextRoute = $route.routes[$location.path()];
var currentPath = current.split('#')[1];
if (nextRoute.restricted && nextRoute.restricted !== currentPath) {
$location.path('/');
alert('You are trying to reach a restricted page!!!!');
}
});
});
You can change the behaviour and redirect user to another link or prevent location change with event.preventDefault();.
Note that if you are not using hashtag (#) in your links (html5Mode) you should change the way to get the current link.
Here's a plunker.
Related
Hi guys am a beginner in mean stack development I have tried to refresh the page after logout.I have tried location.reload(); but it doesn't work tell me the possible code for page reload in this scenario
$rootScope.$on('$routeChangeStart', function (event) {
var storage = userService.isLoggedIn();
console.log(storage);
if (!storage) {
console.log('DENY');
$rootScope.adminlogin = "adminlogin";
console.log($rootScope.adminlogin);
$location.path('/login');
$route.reload();
// $state.go('/login', null, {reload: true});
}
else {
console.log('ALLOW');
$rootScope.admindashboard = "admindashboard";
var path = $location.path();
console.log(path);
console.log(storage);
if(path == '/login'){
$location.path('/');
}
}
});
You should use $window.location.reload() from the the $window service if you want to refresh the page. It does the same thing as the reload button in your browser.
The reason you should use the $window service instead of directly accessing the native window object as per the AngularJS documentation:
While window is globally available in JavaScript, it causes
testability problems, because it is a global variable. In AngularJS we
always refer to it through the $window service, so it may be
overridden, removed or mocked for testing.
On a side note as you stated you are using the $route service, just calling $route.reload() will only reload your controllers and not your entire application.
All you need to do is this little line of Vanilia JS:
document.location.href=document.location.href
EDIT: why is this getting downvoted?
if you are using routes, then on click of Logout just route it to your login page.
Snap shot from demo:
these are my routes:
$routeProvider
.when('/login', {
controller: 'LoginController',
templateUrl: 'modules/authentication/views/login.html',
hideMenus: true
})
.when('/', {
controller: 'HomeController',
templateUrl: 'modules/home/views/home.html'
})
.otherwise({ redirectTo: '/login' });
and when i click on 'Logout' on my page it should do somehting like:
<p>Logout</a></p>
it should redirect to login page as per routes.
For some reason, I can't seem to route to the add screen. What am I doing wrong? Here's my app.js
var moviesApp = angular.module('moviesApp', ['ngRoute']);
moviesApp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/home.html',
controller: 'MoviesController'
})
.when('/add', {
templateUrl: 'partials/add.html',
controller: 'MoviesController'
})
.when('/edit', {
templateUrl: 'partials/edit.html',
controller: 'MoviesController'
});
});
Here's the anchor tag:
Add Movie
Which is contained within my home.html template which is a part of index.html.
The app doesn't crash...it just doesn't do anything.
Any thoughts on what I'm doing wrong?
It may be because of the change in the default hash-prefix in angularjs version 1.6. What you have written works in the given context: Proof
You can confirm this is the case by changing:
Add Movie
to:
Add Movie
If it works look at for possible solutions at:
AngularJS: ngRoute Not Working
If you want to make i behave as you expect (version 1.5) you could choose soultion 3 from the link:
3. Go back to old behaviour from 1.5 - set hash prefix manually
app.config(['$locationProvider', function($locationProvider) {
$locationProvider.hashPrefix('');
}]);
set up a route start event to help debug the problem
.run(function ($rootScope) {
$rootScope.$on('$routeChangeStart', function (event, next, current) {
console.log(event);
console.log(current);
console.log(next);
console.log('$routeChangeStart: ' + next.originalPath)
});
});
just add this to the end of your route config
Just as a side note I would use a state provider over a route provider. State providers let you define a hierarchy. It's a little harder to work with but much more flexible.
Just started using angular and I'm trying to learn as fast as I can. I'm relatively new to SPA's so please bear with me and feel free to tell me if what I want to do is not feasible. What I'm currently stuck on now, is how do I protect my routes when using the ui-router?
What do I want to do?
There are routes that I don't want non-logged in users to access.
For example, /home and /login are okay for anonymous users.
/dashboard should only be for those that are logged in.
I want it so if a user tries to access /dashboard in the future without being logged in, they are not able to.
What have I already tried?
I have tried using the angular-permission module found here: https://github.com/Narzerus/angular-permission
The problem is..I'm not quite sure how to use it (nor if I'm using it properly).
What is currently happening?
In my login controller, once a user submits their username and password it makes a /POST to my web-sever. Once it gets the result, (regardless of what it is for the moment) I've got it redirecting to /dashboard.
Right now nothing should be getting to the /dashboard because no permissions have been set, yet I am (incorrectly) allowed to see the dashboard. I can both (1) successfully be redirected to the dashboard without permission and (2) access /dashboard without permission.
What does my code look like right now?
controllers.js
var controllers = angular.module('controllers',[])
// Login Controller -- This handles the login page that the user can enter
// enter his username & password.
controllers.controller('loginController', function($scope, $state,$location, LoginService){
$scope.email = "";
$scope.password = ""
$scope.login = function(){
var data = ({email:"test", password: "ayylmao"})
LoginService.login(data).then(function(res){
console.log(res);
})
.catch(function(err){
console.log("ERROR!");
console.log(err);
$state.go('dashboard')
})
}
})
app.js
//Definition: The parent module
var myApp = angular.module('clipboardApp', ['services','controllers', 'permission','ui.router']);
//Code below taken from the angular-permission docs.
angular
.module('fooModule', ['permission', 'user'])
.run(function (PermissionStore, User) {
// Define anonymous permission)
PermissionStore
.definePermission('anonymous', function (stateParams) {
// If the returned value is *truthy* then the user has the permission, otherwise they don't.
//True indicates anonymous.
//Always returning true to indicate that it's anonymous
return true;
});
});
//This will be serving as the router.
myApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
//By default go
$urlRouterProvider.otherwise('/home');
//Views are
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'views/home.html',
})
.state('login', {
url: '/login',
templateUrl: 'views/login.html',
controller: 'loginController'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'views/dashboard.html',
controller: 'dashboardController',
data: {
permissions: {
except: ['anonymous'],
redirectTo: 'login'
}
}
});
});
Here is a working example with secured routes. In this example any state start with app. will go via the auth interceptor. $transitions.onBefore hook can be use as follows to satisfy your requirement.
.run(($transitions, $state, $injector) => {
$transitions.onBefore({
to: 'app.**'
}, () => {
const $window = $injector.get('$window');
if (!$window.sessionStorage.getItem('user')) {
return $state.target('login', $state.transition.params());
}
return true
});
});
https://plnkr.co/edit/ZCN2hB34mMEmBJulyaAJ?p=info
In AngularJS 1.4.8 with ngRoute, I am trying to capture search parameters from the URL and then clear them from the URL without reloading the route. This can be achieved easily enough by setting reloadOnSearch: false in my route config. However, after clearing the search parameters from the URL, I do want my route to reload on search.
Is it possible to temporarily enable/disable reloadOnSearch, or do I need to disable it and then manually trigger a reload using $route.reload()?
Here is my current configuration:
angular.module('myApp', ['ngRoute'])
.config(routeConfig)
.controller('MyViewController', MyViewController)
;
function routeConfig($routeProvider) {
$routeProvider
.when('/', {
controller: 'MyViewController',
controllerAs: 'myView',
reloadOnSearch: false,
template: '<h1>Search Params</h1><ul><li ng-repeat="(key, value) in myView.params">{{key}}: {{value}}</li></ul>'
})
.otherwise('/')
;
}
function MyViewController($location) {
var myView = this;
myView.params = $location.search();
$location.search({});
}
Ideally, after calling $location.search({}); I would like to set reloadOnSearch: true.
I have used ng-init="isauthorised()" in my code to get call function after changing every URL
it call when page get refresh but I need this function to get call afer every click on ancher tag
One of the best things to do is to use the route provider to call a function before the page change happens. One example of this (modified from here) is:
$scope.$on('$locationChangeStart', function(event) {
// call your method here
});
The nice thing about this is you know your routine is going to get called and you don't have to modify the code for every anchor tag on the page. By the way, if you are interested in more information check the angular documentation here.
In your application if you want to trigger the function whenever the route changes,Below codes will use
$scope.$on('$routeChangeStart', function(next, current) {
... This Function will trigger when route changes ...
});
$scope.$on('$routeChangeSuccess', function(next, current) {
... This Function will trigger After the route is successfully changed ...
});
if you want to trigger the function, for particular routes, you give it in resolve functions in app.config
for example
myapp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: 'views/login.html',
controller: 'LoginCtrl'
}).
when('/home', {
templateUrl: 'views/home.html',
controller: 'HomeCtrl',
resolve: {
token: function(Token){
... Trigger the function what u want, and give token as dependency for particular route controller ...
}
}
}).
otherwise({
redirectTo: 'index.html'
});
}]
);
Add ng-click="isauthorised()" or do you mean something else?