【问题标题】:AngularJS component: using binding object in controllerAngularJS 组件:在控制器中使用绑定对象
【发布时间】:2017-05-22 07:51:46
【问题描述】:

我使用 Angular 组件(来自this 的第一个示例)。当我在组件中绑定对象时,它可以在模板中访问,但不在控制器中。

js:

function HeroDetailController() {
  console.log("Here I want to use hero.name: ");
  console.log(hero.name); // I want to use binding object in controller, but doesn't work
}

angular.module('heroApp').component('heroDetail', {
  templateUrl: 'heroDetail.html',
  controller: HeroDetailController,
  controllerAs: 'ctrl',
  bindings: {
    hero: '='
  }
});

html:

<hero-detail hero="ctrl.hero"></hero-detail>

模板 html(在这里有效):

<span>Name: {{ctrl.hero.name}}</span>

错误:

ReferenceError: hero 未定义

Plunker:https://plnkr.co/edit/U9CJLs6jgrlsZH6tUdr0

【问题讨论】:

    标签: javascript angularjs angular-components


    【解决方案1】:

    您将在HeroDetailController 上下文中获得bindings 值,即this

    function HeroDetailController() {
      var ctrl = this;
      console.log("Here I want to use hero.name: ");
      console.log(ctrl.hero);
    }
    

    虽然上面行不通。因为它不会在第一个摘要循环中将初始绑定传递给组件。

    为了获得值,您可以在组件上使用 $onInit 生命周期值。

    function HeroDetailController() {
      var ctrl = this;
      console.log("Here I want to use hero.name: ");
      ctrl.$onInit = function(){
        console.log(ctrl.hero);
      }
    }
    

    即使没有$onInit,您也可以直接获取值。同样,您必须更改 $compileProvider 配置,如下所示。(它已在 1.6+ 中引入)

    .config(function($compileProvider){
      $compileProvider.preAssignBindingsEnabled(true)
    });
    

    注意:理想情况下,您不应该在您的应用程序中强制执行上述设置,我只是进行了演示。

    Demo Plunkr

    【讨论】:

      猜你喜欢
      • 2018-03-05
      • 2016-11-09
      • 2018-01-31
      • 1970-01-01
      • 2018-09-29
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多