AngularJS 组件:在控制器中使用绑定对象 [英] AngularJS component: using binding object in controller

查看:22
本文介绍了AngularJS 组件:在控制器中使用绑定对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use Angular component (first example from this). When I binding object in component, it is accessible in template, but isn't in controller.

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(这里有效):

template html (here it works):

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

错误:

参考错误:未定义英雄

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

推荐答案

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

You will get bindings value inside HeroDetailController context which is this

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

虽然上面行不通.因为它不会在第一个摘要周期将初始绑定传递给组件.

Though above would not work. Because it would not pass initial binding to component on 1st digest cycle.

要获取该值,您可以在组件上使用 $onInit 生命周期值.

For getting the value you could use $onInit lifecycle value on component.

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+ 中引入)


Even you could get a value directly without $onInit. For the same you have to change $compileProvider config like below.(it has been introduced in 1.6+)

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

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

Note: Ideally you shouldn't enforce above setting in your application, I just gave it fore demonstration.

演示 Plunkr

这篇关于AngularJS 组件:在控制器中使用绑定对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆