1

I use self invoking functions to include all the javascript code inside an angular controller (I think I saw it somewhere as a best practice). So my controller looks like this:

(function() {
// code
})()

I use gulp to merge all the controllers into one file. My question is this. Does this mean that all of my Javascript code will be invoked and executed when my application starts? If so, I guess that this is not a very good approach. Are there any solutions to that issue? Any comments? Thanks

2 Answers 2

5

No, not all the code gets executed. When you define your Angular modules

(function() {
  'use strict';

  angular
    .module('myModule', [])
    .controller('myController', ['$http', myControllerFunc]);

  function myControllerFunc ($http) {
    // ...
  }
})();

what gets executed are only the angular methods to register the module and the controller. But the actual controller logic is in the callback function, and that gets only called when the controller is invoked (e.g. by the router).

So, its all good, and wrapping the code in anonymous functions is a good idea to keep, for example myControllerFunc, out of the global namespace.

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

1 Comment

Sounds logical. Thanks for the answer.
1

It does not matter wether you define your code into an anonymous function. Javascript client ( browser for this matter ) will have to parse your code either way.

So if you have something callbable in the anonymous function, it will get executed. If you have a declared var with decoupled methods, it will just define that var, just like it would do in a simple separated script inclusion.

Javascript is "parsing" your javascript either way, but will never call methods that are not called by your code. Of course it needs to know that when you call foo( bar ) that foo exists, so it will parse it. It's common javascript.

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.