【问题标题】:Is it pointless to use $onInit in this case在这种情况下使用 $onInit 是否毫无意义
【发布时间】:2017-11-17 04:33:35
【问题描述】:

我有一个 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 的好处是什么,我希望在哪里看到这个(这些)好处?

【问题讨论】:

    标签: angularjs angularjs-components


    【解决方案1】:

    $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"
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 2017-03-28
      • 2016-08-26
      • 2012-10-05
      相关资源
      最近更新 更多