Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

javascript - AngularJS component: using binding object in controller

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>

template html (here it works):

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

Error:

ReferenceError: hero is not defined

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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.

Demo Plunkr


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...