AngularJS component: using the binding object in the controller

I am using the Angular component (first example from this ). When I bind an object in a component, it is available in the template, but not in the 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 (it works here):

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

Error:

ReferenceError: the hero is not defined

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

+4
source share
1 answer

You will get a value bindingsinside the context HeroDetailController, whichthis

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

Although the above will not work. Since it will not transfer the initial binding to the component in the 1st digest cycle.

$onInit .

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

$onInit. $compileProvider config, ( 1.6 +)

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

. , .

Demo Plunkr

+8

Source: https://habr.com/ru/post/1666098/


All Articles