angular 组件启动时初始化函数的模式

Pattern to initialize a function when angular component launch

最近我在 angular 组件启动时初始化了一个函数。

我看过这个 comment 我想知道它是否是一个好的模式或者可以更好地声明函数并在下面的代码之后调用它:

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

    // function call to launch
    init();

  }
)

或如评论中所述:

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

你用过什么,甚至在使用最后一种方法时是否存在已知问题?

Till angular 1.4.x john Papa 风格指南更喜欢使用第一种方法在最后调用 init 函数,确保一切都在之前进行初始化。我也推荐。

你不能在这里考虑第二种选择。它是一个 IIFE,更有可能在隔离范围内定义您的函数,而不是在全局范围内声明它们。

除此之外,如果你现在专门谈论 component 那么你应该使用 $onInit angular 组件生命周期挂钩来调用初始化代码。

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'
})

我建议你使用 "bindable members on top" 的原则,并使用函数声明而不是函数表达式,这样函数就可以隐藏在控制器的底部并被提升。

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


    // function call to launch
    init();

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

  }
)

参考:John Papa Angular Style guide