javascriptangularjsangularjs-directiveangularjs-bindings

AngularJS Directive binding to controller


I'm trying to figure out AngularJS directives. I've got the following JSFiddle with an example of something I'm trying to do. https://jsfiddle.net/7smor9o4/

As you can see in the example, I expect the vm.alsoId variable to be equal to vm.theId. In the template vm.theId displays the correct value but vm.alsoId does not.

What am I doing wrong? How could I accomplish my goal.

If it helps the final idea is to execute something as the following:

function directive(service) {
  var vm = this;
  vm.entity = null;

  init();

  function init() {
    service.getEntity(vm.theId).then(function (entity) {
      vm.entity = entity;
    });
  }
}

Solution

  • As you've noticed, the bindToController bindings are not immediately available in the controller's constructor function (unlike $scope, which are). What you're looking for is a feature introduced with Angular 1.5: Lifecycle Hooks, and specifically $onInit.

    You had the right idea; simply replace your init function definition and invocation as follows:

    vm.$onInit = function () {
        service.getEntity(vm.theId).then(function (entity) {
          vm.entity = entity;
        });
    };
    

    And here is your updated fiddle. (Alternatively, without this solution, you'd have needed a watch.)