$routeProvider , Clicking same link more than once - angularjs

Below is my partial angularJS code which implements routeprovider
TicketApp.config(function ($routeProvider) {
$routeProvider
// route for Create Ticket Page
.when('/CreateTicket', {
templateUrl: '../Ticket/Create',
controller: 'CreateCtrl'
})
// route for Open Ticket Page
.when('/OpenTickets', {
templateUrl: '../Ticket/MyTickets',
controller: 'MyTicketsCtrl'
})
// route for All Users Search Page
.when('/SearchUsers', {
templateUrl: '../Account/AllUsers',
controller: 'AllUsersCtrl'
})
..........
When user clicks SAME link more than once, only the
first click makes an AJAX request ,the subsequent requests
do not.
What needs to be modified so that subsequent requests to SAME link also make an AJAX call.
EDIT :
I also added below code
TicketApp.run(function ($rootScope, $templateCache, $location) {
$rootScope.$on('$routeChangeStart', function (event, next, current) {
$templateCache.remove(current.templateUrl);
});
});
did not work for me.. :(

Why do want to execute Ajax requests? It is only one request required to load the template from the server. There is no need to load it multiple time, because it shouldn't change or your architecture is not really compliant to Angular.
You could probably invalidate the templateCache and force Angular to reload the templates.

Might be this will work for your case .When the user will click the Button(the ajax call start's) you just hide it(button) once the AJAX call return a response back then show it(button).

Related

reload page in angular js after logout

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.

$location.path or $location.url doesn't trigger the ngRoute controller

I have a route defines as follows:
$routeProvider.
when('/projects/', {
controller: 'ProjectCtrl',
controllerAs: 'project_ctrl',
templateUrl: '/static/app/partials/project.html'
}).
After the login finishes I need the user to land on this link, hence in my controller I am using this:
vm.login = function(form) {
if (form.$valid) {
loginService.login(vm.loginFormData.username, vm.loginFormData.password);
loginService.setUpUser()
$location.url("/projects");
}
}
But unfortunately the controller associated with this view is not triggered, that is ProjectCtrl is not triggered. However when I click on the navigation link which uses in the dom, it works fine. Can someone please guide me here, may I am missing something conceptual.
Hence the larger question is how do I redirect a user in the controller using some APIs which also complies with ngRoute based controllers.
Try removing the last / in url so it matches $location.url("/projects");
$routeProvider.
when('/projects', {

Close socket.io connection from client on Url change

I am using Socket.IO to pull data for plotting graphs, on
var socket = io.connect();
my Node js server's io.on('connection', function(socket){}) starts a function, on interval of every 1 sec it emits the data to the clients connected.
I want the socket to close on change of Url (away from app) from client and server should stop emitting data.
As we discussed in the comments to the question, you're looking to disconnect from the socket when your Angular ngRoute controller partial route changes away from a given state; this is different as a partial routing single-page application doesn't trigger a fully new page, but rather loads up partial content (defined in partial/template files or script definitions). This is key to why Furkan Başaran's answer won't work for you out of the box for changes between Angular routed states within the same SPA.
I've prepared a plunker that is a fairly basic AngularJS app; it has three html partials that it shows at three corresponding routes using ngRouter and invokes a function to <do-something> when the route change occurs. In this case, it's throwing an alert function, whereas in your case you may which to check for whether or not the route is to anything not the route you want to provide the socket functionality on.
Note: there is a change on every time the Angular app registers a route changes, so the initial establishment will register with a blank value for the / state, then every time it changes from the load, including the otherwise.redirectTo('/destination1').
Plunker (embedded) link:
http://embed.plnkr.co/ayjgYCsox7RGl5OjyGsV/
Quick break down:
I start by defining my handling function to be triggered on ngRouter changes. The passed value is the registered route (after the / or /index.html), such as /potatoes as is a case in my example. This is where you should perform your socket.disconnect();.
function changedMyPartialRoute(val){
alert('url has changed to: ' + val);
}
After I defined my app (angular.module('appName', [...), I define the config for my ngRouter setup.
.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider
.when('/meat', {
templateUrl: 'meat.html',
controller: 'MeatCtrl',
controllerAs: 'meat'
})
.when('/potatoes', {
templateUrl: 'potatoes.html',
controller: 'PotatoCtrl',
controllerAs: 'potato'
})
.when('/bacon', {
templateUrl: 'bacon.html',
controller: 'BaconCtrl',
controllerAs: 'bacon'
})
.otherwise({
redirectTo: '/meat'
});
}])
Finally, I invoke a run block on the app (module) to provide that hook into detecting the change. I'm passing in $rootScope and $location and it performs a $watch on the $rootScope to detect a change in the $location.path(). That whole run block:
.run( function($rootScope, $location) {
$rootScope.$watch(function() {
return $location.path();
},
function(val){
// the handling function from step 1
changedMyPartialRoute(val);
});
})
If you need to do something with $rootScope, as I suspect you might, you'll need to hand off the $rootScope handle through the changedMyPartialRoute function or just define your handling inline in the function callback in the .run block. This HTML5rocks.com tutorial shows their configuration in their Angular app by hooking into $rootScope, as opposed to $scope as you mentioned in the above comments.
I hope that helps!
When client closed connection close automatically, if you want see this, write this code to your node server and look to console when closed your client tab.
io.on('disconnect', function() {
console.log("Connection disconnected");
})

AngularJS - Ionic : execute code in controller when coming back to it

I'm new in AngularJS Community and I'm developping my first app with this Framework.
I created a new controller with this code :
.controller('AccountCtrl', function($scope, $location) {
alert('test');
})
And my route :
.state('app.account', {
url: "/account",
views: {
'menuContent': {
templateUrl: "templates/account.html",
controller: 'AccountCtrl'
}
}
})
The alert popup is shown the first time I access to the controller. But, if I change URL and I come back to AccountCtrl (with a classic html a), the alert popup is not shown again.
Could somebody explain to me why ?
Thanx for your help !
In Ionic Framework views and controllers will be cached by default. You ma add a listener to the views scope to receive a notification when the view is re-active again. For more information see: http://ionicframework.com/docs/api/directive/ionView/
and http://ionicframework.com/docs/api/directive/ionNavView/
You may also disable the cache on a view <ion-view cache-view="false">
.controller('AccountCtrl', function($scope, $location) {
$scope.$on('$ionicView.beforeEnter', function () {
// update campaigns everytime the view becomes active
// (on first time added to DOM and after the view becomes active after cached
alert('test');
});
})`
to reload Controller each time in ui router, use reload: true option on the .state
$stateProvider
.state('app.account', {
url: "/account",
reload: true //forcefully reload route and load controller again
})

Check if user is logged in before template load

I use angularjs with ui-router library. Lets say I have some routes for admin and some routes for user. If admin or user is logged in I want to show some page for them (admin.html for admin and user.html for user, for example), otherwise login.html
On the backend I have a special url, like /auth/status/, which gives me information about the user (if he's logged and which role he has)
There are some situations I can't figure out how to handle:
I go to '/' url. The application loads. I have a run method for my app module. But how can I check if the user is logged in, when it happens asynchronously? Well, I have this and it works somehow, but I'm not sure if this is a good solution:
app.config(['$stateProvider', '$routeProvider',
function($stateProvider, $routeProvider) {
$stateProvider
.state('admin', {
abstract: true,
url: '/',
templateUrl: 'templates/admin.html'
})
.state('admin.desktop', {
url: 'desktop',
templateUrl: 'templates/desktop.html'
});
}]);
app.run([
'$http',
'$rootScope',
'$location',
'$state',
'userRoles',
function($http, $rootScope, $location, $state, userRoles) {
var DEFAULT_ADMIN_STATE = 'admin.desktop';
var promise = $http.get('/auth/status/');
promise.then(function(response) {
$rootScope.isLogged = response.data.logged;
$rootScope.userRole = userRoles[response.data.role];
if (!$rootScope.isLogged) {
$state.transitionTo('login');
} else {
switch (response.data.role) {
case 'admin': $state.transitionTo(DEFAULT_ADMIN_STATE); break;
}
}
}, function(response) {
$location.path('/login');
});
}]);
Though I don't understand: if I go to / url I should get an error because it's abstract. Instead when $http.get request is resolved (I put 2 seconds sleep in backend to check that) I transition to admin.desktop state. I'm confused what happens in which order: state loads template or app.run function with some ajax requests...
The main question is, when I go to /#/desktop how can I first check if user is logged (send a request to /admin/auth/ and check what it returns) and only then decide what to do (transition to login or desktop state)?
I found Delaying AngularJS route change until model loaded to prevent flicker this, but again still a little fuzzy for me. Resolve property seems like a solution when I want to load a list of entities and then show the template. But I want to have some "before" function for ALL states which just checks if user is logged and has a correspond role (one moment: I do not want to use /admin/entites or /user/entities urls, want to have just /entitites. As I get it several states may have the same url). So basically it looks like if I go to /someurl I want to run method wait until it gets ajax response and after that transition to some state. Instead the state corresponding to /someurl load a template...
Also I found an article about authentication in angular but author uses cookies which is not async thing
Update: when I use cookies for checking if user is logged and I go to /#/desktop I still have it rendered, and $state.transitionTo doesn't work..
You should check it before page load:
I cannot write full example now, but in common you should do like this:
.run([ ..., function(....) {
$scope.$on('$routeChangeStart', function(next, current) {
... check cookie here ...
});
}]);

Resources