1

Recently I had initialize a function when the angular component launch.

I had seen this comment and I'd like to know if is it a good pattern or could be better declare the function and call it after such the code below:

angular.module('app').controller('control',[...,
  function(){
    ...
    var init = function () {
      //what i wish run on launch
    };

    // function call to launch
    init();

  }
)

or as mentioned in comment:

(function(){
    //code to run
}());

What do you have been used or even are there known problems when use this last approach?

D. Pazeto
  • 43
  • 8

2 Answers2

1

I would suggest you use principal of "bindable members on top" and use function declarations instead of function expressions so that functions can be hidden at bottom of controller and will get hoisted.

angular.module('app').controller('control',[...,
  function(){


    // function call to launch
    init();

    // declare functions at bottom
    function init() {
      //what i wish run on launch
    }

  }
)

Reference: John Papa Angular Style guide

charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

Till angular 1.4.x john Papa style guides preferred to use 1st approach to call init function at the end by ensuring everything got initialize before. I recommend the same.

You can't consider a second option here. It's an IIFE, its more likely to define your function in isolated scope instead of declaring them in global.

Apart from that these days if you're specifically talking about component then you should use $onInit angular component lifecycle hook to call initialisation code.

angular.module('app').controller('control',[...,
  function(){
    var vm = this;
    vm.$onInit = $onInit;


    function $onInit() {
      //what i wish run on launch
    };
  }
)
.component('myComponent', {
  controller: 'control',
  templateUrl: 'sometemplate.html'
})
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • I didn't use this way because isn't easier than the first, but now I know how to named this function ( IIFE ). Nice! thank you for your explanation. – D. Pazeto Jul 08 '17 at 22:23