Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run javascript function when ui-router state changes?

In a Angular App i am using ui-router to handle navigation etc. In a separate script file, i have a function like so;

$(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 as it is not part af any Angular function, i get an error when i reference it, as i cannot find it.

What should i be doing, instead of the above?

like image 767
brother Avatar asked Mar 08 '16 12:03

brother


2 Answers

Hello you can also add your jquery code into the onEnter:function() of your state , as onEnter is executed each time you change the state and a controller is loaded.

example(a 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.

like image 92
Theo Itzaris Avatar answered Nov 03 '22 20:11

Theo Itzaris


Here is how I would do.

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 within IIFE it wraps everything in closure and prevents leaks as well as provides a layer of security.

Hope this helps!

like image 39
Dave Amit Avatar answered Nov 03 '22 20:11

Dave Amit