最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS component: using binding object in controller - Stack Overflow

programmeradmin0浏览0评论

I use Angular ponent (first example from this). When I binding object in ponent, 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')ponent('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:

I use Angular ponent (first example from this). When I binding object in ponent, 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').ponent('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

Share Improve this question edited Jan 8, 2017 at 18:09 mkczyk asked Jan 7, 2017 at 17:47 mkczykmkczyk 2,7203 gold badges32 silver badges43 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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 ponent on 1st digest cycle.

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

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 $pileProvider config like below.(it has been introduced in 1.6+)

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

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

Demo Plunkr

发布评论

评论列表(0)

  1. 暂无评论