Can't get $anchorScroll working on $stateChangeSuccess? - angularjs

I'm trying to adapt the answer give in this similar question How to handle anchor hash linking in AngularJS. I need to be able to use it with ui-router. I've tested anchor scrolling as a clickable function in my controller and that is working. Here is the code for that
$scope.anchor = function () {
console.log('test');
$location.hash('comments');
$anchorScroll();
};
If I try to invoke that function immediately nothing happens
$scope.anchor();
If I try to invoke it on a $stateChangeSuccess nothing happens. I threw in a log for sanity and that is firing. I also tried a trick to prevent further routing logic from kicking in. It was mentioned in the linked post but I'm not sure if it's necessary for my case.
app.run(function ($rootScope, $location, $stateParams, $anchorScroll) {
// allow anchorScrolling
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
console.log('stateChangeSuccess');
var old = $location.hash();
$location.hash('comments');
$anchorScroll();
//reset to old to keep any additional routing logic from kicking in
$location.hash(old);
});
});
I'm guessing that I'm running into race conditions or my anchor scroll is somehow triggering another route change. But I can't figure out how to track these issues down. Any thoughts?
EDIT: Update I removed the $location.hash(old); and put the rest of the $anchorScroll pieces into a timeout function and it's now working. I also added in the $stateParams.scrollTo to make this useable with query params. Any ideas as to what is causing my race condition and how this might be solved without a $timeout function?
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
console.log('stateChangeSuccess');
$timeout(function() {
$location.hash($stateParams.scrollTo);
$anchorScroll();
}, 300);
});

From $anchorScroll documentation
It also watches the $location.hash() and scrolls whenever it changes to match any anchor. This can be disabled by calling $anchorScrollProvider.disableAutoScrolling().
Try removing $location.hash(old);
If that fixes it, use $anchorScrollProvider.disableAutoScrolling() to disable it reacting to another state change.

Related

How to call a function in all controllers in AngularJs

I have a function validateSesion that i need to call every time a controller is executed.
There is a way to trigger the function without putting the call to the function in all the controllers?
The way I would recommend accomplishing such a call would be to create event handlers for your route changes. This way every time you change your route or state (if you are using ui-router) you can run your code.
You would place this in your app's run function and attach the event handlers to the $rootScope as shown below:
angular.module('app', [
//Your Dependencies Here
]).run(init);
function init($rootScope, sessionService) {
//ngRoute
$rootScope.$on('$routeChangeStart', function (angularEvent, next, current) {
sessionService.validateSession();
});
//ui-router
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
sessionService.validateSession();
});
}

UI-router : $state.current.name shows empty

Sometimes state which i define is not render and shows blank page.
And at this time when i try to see from console which state is this, it shows like below.
state name shows empty, which is not defined in my app.
Anybody know about this issue please help me.
I am guessing you see the full object in console because it gets filled later and the browser reacts..
Try to include your block with $state into a $timeout(). It's a trick to wait for the $digest cycle to be over before getting the value.
$timeout(function() { console.log($state.current.name); });
or
$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams) {
var statename = toState.name
console.log(statename) })

Run a function every time an angular route is navigated to

I want to run a function every time an Angular route is navigated to.
One option is I just add myFunction() to the top of every controller. Seems really repetitive. Is there a better way to run myFunction() every time $location changes?
If you are using ui-router, you can simply bind a function to the $rootscope.
See the stateChange section: https://github.com/angular-ui/ui-router/wiki#state-change-events
$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams){ ... })

AngularJS UI-Router event when changing route

Using ngRoute once can hook up in event: $routeChangeStart and do different actions ...
app.run(function ($rootScope, $location) {
$rootScope.$on("$routeChangeStart", function (event, next, current) {
................
Is it possible to achieve the same using UI-Router?
Yes it's possible:
$rootScope.$on("$stateChangeStart",
function (event, toState, toParams, fromState, fromParams) {
Or just use
$scope.$on("$stateChangeStart",...);
If you want this to be triggered on a single page.
Check this answer here, that's the correct way to fix it. Removing all listeners could have unknown effects as there might be other places where listeners are added. You need to remove the one you added, not all of them.
Check this issue: Angular $rootScope $on listeners in 'destroyed' controller keep running
Copying code here for completeness too:
animateApp.controller('mainController', function($scope, $rootScope, service) {
$scope.pageClass = 'page-home';
var unregister = $rootScope.$on('service.abc', function (newval) {
console.log($scope.$id);
});
$scope.$on('$destroy', unregister);
});

Good pattern for a loader in Angular app?

I'm working on an AngularJS-based business app. In most common scenario before I show the view I'm loading some data by making a few $http POST calls. I want to show a loader in the meantime. So far I've done it by $broadcasting an event and catching it elsewhere with dedicated controller. This allows me to have a single loader per web page, which is fine. At least for now.
But maybe are there any better approaches?
Instead of broadcasting the events yourself you can take advantage of the start and finish events that the route provider are throwing apon view-change.
Angular router ($route)
$rootScope.$on('$routeChangeStart', function(e) {
openLoader();
});
$rootScope.$on('$routeChangeSuccess', function(e) {
closeLoader();
});
ui-router ($state)
$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
openLoader();
});
$rootScope.$on('$stateChangeSuccess', function(e, toState, toParams, fromState, fromParams) {
closeLoader();
});
And you might want to add a filter here if you have states/routes where the loader should not be displayed.
The approach:
You can have a block level element in your main page containing gif loader or "Loading..." text. The visibility of this element should be hidden by default.
Inside Request Interceptor you can make the block level element visible and inside Response interceptor if all the request are completed and there are no pending requests you can hide this block level element.
You can achieve this functionality in a common place and so far have found this as a best approach

Resources