7

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?

6
  • is there a reason that you wrap the function in $()? Commented Mar 8, 2016 at 12:46
  • None other, than it uses jQuery. Commented Mar 8, 2016 at 12:48
  • do you have access to the $routeChangeStart Commented Mar 8, 2016 at 12:53
  • Not within the above function where it currently sits. But i have within my Angular app i would presume? Commented Mar 8, 2016 at 12:54
  • 1
    Write the function directly,i.e. instead of $(function(){ function doSomething() { /* ....... */ } }); do function doSomething() {/* ..... */}. But it would pose a security risk! I would not suggest that, as @Zamboney mentioned, its quick and dirty ... :) Commented Mar 8, 2016 at 13:09

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

7

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!

5 Comments

I just tested this, and it works. However, i missed something. I have calls to API's on most of my states. This API populates a list. Whenever this list changes, and are fully loaded, i want to calculate the height, to set the height of the element. It seems statChangeSuccess is loaded before this is the case. I guess i have to deal with the promise of some sort?
Hmm, I'm still not clear if I understand the flow properly. Would you be able to prepare a quick bare minimum js-fiddler or plunker ? It will make the process much faster! Wouldn't you agree?
For eg. When you say, "I have calls ...... API populates a list", my question is where do you store the list? in $rootScope? in some service?. If $rootScope then you could just do $watchCollection to look for changes and then trigger your code. There are many possible answers :( and I won't be able to help until I have some type of working code to play with !
I understand, but i think i got it working now with help from your example. Thank you very much! :)
Use event.preventDefault() to prevent the transition from happening inside event function.
1

If you are the one controlling the state changes via $state.go() for example, you can amend it:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.