AngularJs : Multiple clicks on same button is not working - javascript

I have created a web page in Angular Js. Whenever I navigate to some other page from Home page and click on Home button from that page it navigates back to Home page which is expected and working fine. But when again I click on Home button then I'm expecting a page refresh (because currently it is Home page) but it is not happening.

Angular does not reload the view when the $location of the route you are trying to go to is the same as the current route you are on.
You can use the reload() method to achieve this.
See https://docs.angularjs.org/api/ngRoute/service/$route
(Make sure you switch the api version to match the Angular version you are using)
For a cleaner solution (imho) than using search parameters see the following code (I am using controllerAs syntax):
angular.module('app').controller('MainController', [
'$location',
'$route',
function ($location, $route) {
var main = this;
main.goToHome = function () {
if ($location.path() === '/') {
$route.reload();
}
};
}
]);
in combination with calling that function on your home button link on click:
Home
This function checks the location when you click your button, if the location is / then it reloads the view.
Of course you can replace the route url with whatever url you use for your home route.

The following is an untested, alternative solution I came up with.
In your routes configuration object for the home page (which I am assuming has a url of /home), specify the following parameters:
{
// ...
reloadOnSearch: true,
redirectTo: function (routeParams, path, search) {
if (search.redirected) {
// don't redirect, so return same path + search
return '/home?redirected=true';
} else {
return '/home';
},
// ...
}
The thinking is that when you link to /home, the redirectTo() function will fire and redirect you to /home?redirected=true. That will be a change to the search parameter, so the route should reload correctly due to specifying reloadOnSearch: true. Since the home page links will always be pointing to /home, the page should always reload.
It's a bit ugly, and will likely cause the home page controller to run twice when going from some other page back to the home page, but if you can't get any other way to work, this one might be worth a try.

Related

angular ui router back button issue

'use strict';
angular.module('cbApp')
.config(function ($stateProvider) {
$stateProvider
.state('search', {
url: '/college/search',
templateUrl: 'app/collegesearch/views/collegesearch.html',
controller: 'collegeSearchCtrl'
})
.state('searchCollegeFilter', {
url: '/college/search/:streamId?cities&courses&branches&ordering',
templateUrl: 'app/collegesearch/views/collegesearch.html',
controller: 'collegeSearchCtrl'
});
});
Here my application calls the 1st state i.e 'search' with a url /college/search. Inside the controller I transition to another state searchCollegeFilter.
What I wanna do is navigate the user back to the back they came from when they click the browser back button. Say they came from '/' I want them to go back to home page. But in browser back history there are 2 entries for college/search. I want this to happen only for the 1st time.
For this northing is do with angularjs, the thing is you need to watch browser back event before navigating "window.onhashchange". By observing that you can make you check and can redirect default page
What I am doing in a different application would serve the purpose:
Basically: Specify parent states!
-> Then the logic is becoming easy.
You don't have to be specific about history or back button or anything like that.
Basically:
-> Check in
$rootScope.$on("$onstateChange", ...
-> If
the fromState.parent equals toState.parent
then $window.history.replaceState({}, "My Detail State Page", $state.url(toState)

Redirect to a different route from within a ngRoute $routeProvider resolve

In my app I have a situation in which based on a certain condition, if a user access a certain route ('/checkinsuccess') before that controller and view loads a function gets run that checks if a certain flag is true using routeProviders resolve property. If this flag is true it redirects to a new route. Unfortunately it seems like the initial view and controller that I'm trying to redirect away from ('/checkinsuccess') are loading before the function being called in the resolve property finishes. This is causing issue since that initial view runs an auto logout function. Is there a way to run the check before the initial route loads, I thought that's what resolve did? Here's a piece of my code.
.when('/checkinsuccess', {
controller: 'thankuctrl',
templateUrl: 'views/MobileCheckin/checkin-success.html',
resolve: {
checkForWorkflowUpdates: function($location){
checkForWorkflowUpdates($location)
}
}
// check if workflow update has been made and load that route if true.
function checkForWorkflowUpdates($location){
var selectedForms = JSON.parse(sessionStorage.getItem('selectedForms'));
if (selectedForms) {
if(selectedForms.workersComp){
$location.path('/workerscomp');
} else if (selectedForms.motorVehical) {
$location.path('/autoaccident');
}
}
}

"Re" resolve resources with angular ui router without reload

I am using the following code to resolve a resource when the main state is loaded. Is it possible to re - resolve the resource without reloading the page? I am avoiding reload so that the user experience is not affected.
$stateProvider
.state('main', {
url: '/',
templateUrl: 'publicApp/main.html',
controller: 'MainCtrl as mainCtrl',
resolve: {
userData: ["UserApi", function (UserApi) {
return UserApi.getUserData().$promise;
}]
}
})
.controller('MainCtrl', function (userData) {
console.log(userData.something);
})
Since is a public site, the user can visit any page without logging in but when the user logs in the page must customize based on the user data.
EDIT
I am using a modal for login so the state doesn't reload after logging in, I was thinking of throwing an event on $rootScope and then add listeners in controllers to load them again. But this doesn't look good, so I am looking for a better way
I currently have two options:
Reload page - will effect the user experience, so its the last option
Throw an event for the login modal and catch it in other controllers
Any better ideas?
Try using state reload once promise is resolved
$state.reload();

prevent users to navigate back to specific routes with backbone

I am new to backbone and I want to implement a very simple auth using backbone router.
I am actually using only the router from backbone in my app. When I start the app I render a login view and I also init the backbone router (Backbone.history.start();)
If login succeeded I call router.navigate('mainmenu', { trigger: true, replace: false }); to navigate to a new route where I render the main menu, but when I click on the browser's back button I navigate back to the login view.
Before navigating to the previous view (the login view) I want to ask the user if he wants to logout first, and if logout process goes well, then he is redirected to the login view.
How can I achieve that? I checked few other questions, but the answer is too complicated for my use case. I just want to prevent users to navigate back to specific views if they're logged in.
#Dethariel thanks for the answer. I successfully implemented some kind of session, using the built-in Backbone router. I started with their small example snippet from the Backbone.Router execute method backbone router execute snippet and did something similar to bellow:
var Router = Backbone.Router.extend({
// define routes and calkbacks
// ....
// define routes and calkbacks
execute: function(callback, args) {
// execute will be called before the callback for each specific route
// get the next route in here
var nextRoute = Backbone.history.fragment;
if(user.LoggedIn()){
// check if nextRoute is '#login*'. I could make other checks as well
if(nextRoute.indexOf('login')>-1)
prompt('Log out?');
// else continue routing
else if (callback) callback.apply(this, args);
}
else if (callback) callback.apply(this, args);
}
});
This is very minimal, and I don't think it's the best or secure way, but it's a good starting point for me.
You can add a backbone route which will handle the login page (if you haven't done that yet). Once this route is hit, you do (pseudo-code follows):
if (user.isLoggedIn()) {
if (showLogoutPrompt().decision === "logout") {
user.logout();
}
}
Hope this helps.

ui-router change state via a URL address?

I'm having trouble transitioning to another view state when I only have the full URL path. The ui-router says to use $state.transitionTo or $state.go but those require the state name.
I tried to change the current URL using $location.url(path) but nothing happens.
Is $location.url(path) the correct way, and something is wrong with my setup or is there another way to do it?
Here is my configuration for the home page:
$stateProvider.state(
{
name: 'home',
url: '^/',
templateUrl: "/home.html"
}
);
Here is my config for the app.
cgTag.App.Config.Config = function($httpProvider, $locationProvider, $sce)
{
// Let CakePHP see $http requests as AJAX
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
// use HTML5 non-hash URLs
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('!');
// add all the CDN domains to the white list so that URLs are not blocked by Angular.
var cdn = cgTag.AppData["Domain"].replace(/^www\./, "http://s*.") + "/**";
$sce.resourceUrlWhitelist(['self', cdn]);
};
cgTag.Angular.config(['$httpProvider', '$locationProvider', '$sceDelegateProvider', cgTag.App.Config.Config]);
If the current browser url is http://www.cgtag.com/movies then calling $location.url("/") should go to the home page, but nothing happens.
I needed to call $scope.$apply() after calling $location.url(path).
Could be because the code was in a keydown event handler.
you need to use $location.path() instead $location.url()

Categories

Resources