1

I'm developing an application which has the following directive and controller:

function directive() {
  return {
    restrict: 'E',
    template: template,
    controller: 'MessageChatAppController',
    controllerAs: 'vm',
    scope: {},
    bindToController: {
      recipient: '=?'
    }
  };
}

function Controller(MessageChatAppService, UserFactory, $scope) {
  let vm = this;

  console.log(vm);
  console.log(vm.recipient);
  console.log($scope)

  vm.message = '';

  vm.sendMessage = _sendMessage;

  function _sendMessage() {
    MessageChatAppService.sendMessage(vm.message, UserFactory.model.email);
  }

  function _connectUser() {
    MessageChatAppService.connectUser(UserFactory.model.email);
  }

  _connectUser();
}

When the following is executed:

console.log(vm);
console.log(vm.recipient);
console.log($scope)

It returns: https://drive.google.com/file/d/1UtWI5WKydF-Hdus_Kilj-A1DxAAG4duz/view?usp=sharing

As you can see the recipient object has data but of course I can't access by using vm.recipient because it's owned by the Controller. Searching the internet I found that the issue happens due to a delay in the controller initialization, a solution to this would be using $onInit, but as I never needed $onInit in order to make the controller access the directive variables, I don't want to use it. Is there any other way to make it work?

1 Answers1

0

Initialization logic that relies on bindings being present should be put in the controller's $onInit() method, which is guaranteed to always be called after the bindings have been assigned. This is the robust way to write your controller. Just because you have been lucky up until now, is no reason to continue using flaky and fragile coding methods.

For more information, see

georgeawg
  • 48,608
  • 13
  • 72
  • 95