在这种情况下使用$ onInit是否毫无意义

时间:2017-06-14 21:01:29

标签: angularjs angularjs-components

我有一个angularJS(1.5+)组件,它有一些绑定到父控制器变量的单向绑定属性。此组件直接在绑定对象中使用这些属性,不需要设置任何局部变量。

当页面加载时,组件的绑定被初始化并绑定到默认值,因为父控制器将其变量初始化为默认值。

示例代码:

App.component('myComponent',{
    bindings:{
        binding_1: '<',
        binding_2: '<'
    },
    template:'<div ng-show="$ctrl.binding_1">' +
    '<input type="button" ng-click="$ctrl.clicked()">' +
    '</div>',
    controller: function () {
        var ctrl = this;

        // would ctrl.$onInit = function(){...} be beneficial here at all?

        ctrl.clicked = function(){
            console.log("ctrl.binding_2.text");
        }
});

如果组件仅使用其绑定属性,并且在页面加载时通过父控制器变量将这些属性初始化为默认值,那么实现$ onInit的好处是什么以及我期望在哪里看到(这些)福利?

1 个答案:

答案 0 :(得分:0)

$ onInit是组件的初始化生命周期钩子。你应该在那里执行初始化逻辑。对于代码示例,组件绑定可能是可访问的,因为它们是在单击处理程序中访问的。这是一个演示$ onInit的小型演示。

Component Initialization with $onInit

angular.module('app',[])
.controller("MyController", function(){
  var ctrl = this;
  ctrl.title = "Hello World";
})
.component("myComponent", {
   bindings:{
        bindingOne: '<'
    },
    template: ' <h1>{{ctrl.title}}</h1>',
    controller: function(){
      this.$onInit = function(){
        this.title = this.bindingOne;
      }

    },
    controllerAs: "ctrl"
})

Component Initialization Without $onInit

  angular.module('app',[])
    .controller("MyController", function(){
      var ctrl = this;
      ctrl.title = "Hello World";
    })
    .component("myComponent", {
       bindings:{
            bindingOne: '<'
        },
        template: ' <h1>{{ctrl.title}}</h1>',
        controller: function(){
          this.title = this.bindingOne;
        },
        controllerAs: "ctrl"
    })