Run javascript function when ui-router state changes?

In an Angular app, I use ui-router for navigation, etc. In a separate script file, I have a function like this:

$(function () { function doSomething(){ if ($('.thisclass').length) { $('.thisclass').css({ 'height': someHeight }); } } }); 

My problem is that whenever the state changes, I want to run the above function. But since it is not part of any Angular function, I get an error when I refer to it, since I cannot find it.

What should I do, not higher?

+6
source share
3 answers

Here is how I did it.

app.js

 (function(){ angular.module('app',[]); /* other code like configuration etc */ })(); 

SomeService.js

 (function(){ angular.module('app'); .factory('someService',function(){ return { doSomething: function(){ $('.container-fluid').css('display', 'none'); } }; }); })(); 

app.run.js

 (function(){ angular.module('app') //Inject your service here .run(function($rootScope,someService){ //Look for successful state change. //For your ref. on other events. //https://github.com/angular-ui/ui-router/wiki#state-change-events $rootScope.$on('$stateChangeSuccess', function() { //If you don't wanna create the service, you can directly write // your function here. someService.doSomething(); }); }) })(); 

Always wrap your angular code in IIFE , it completes everything in closure and prevents leaks, and also provides a level of security.

Hope this helps!

+5
source

Hello, you can also add jQuery code to the onEnter:function() your state, since onEnter is executed every time the state changes and the controller loads.

example (login state):

 .state('login', { url: '/login', controller: 'LoginCtrl', templateUrl: '/assets/modules/login/login.html', resolve: { user: ['authService', '$q', function (authService, $q) { if (authService.user) { return $q.reject({authorized: true}); } }] }, onEnter: function () { //i hide header tabs, you can add your code here $('.container-fluid').css('display', 'none'); }, onExit: function () { //onExit is executed when we leave that state and go to another } }); 

Hope helps, good luck.

+5
source

If you control state changes through $ state.go (), you can change it:

 $state.go('somewhere', { 'place': 'somewhere' }).then(() => { // write your function here }); 
0
source

All Articles