AngularJS component: using binding object in controller

前端 未结 1 1998
梦谈多话
梦谈多话 2020-12-21 04:45

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:

fu         


        
相关标签:
1条回答
  • 2020-12-21 05:38

    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

    0 讨论(0)
提交回复
热议问题