What is the correct way to access the controller that is required in the controller directive?

I have a directive with the property require:

require: '^testBox'

Now I want to get the testBox controller inside the controller of my directive. How am I supposed to do this?

I tried to do this:

controller: function(){
  this.testBox.user
}

but it looks like it is not working. It is clear to me how to get the required controller inside the function link. But is there any way to get it inside the controller without using link?

Code on the plunker .

+4
source share
2 answers

. . Plunker. , ; TextBoxCtrl UserCtrl pre post, . - watcher varibale , textBox. , UserCtrl watcher. :

{{ user.textBox.name }}

user:

link: function($scope, $element, $attrs, ctrl) {
  $scope.textBox = ctrl
},
controller: function($scope) {
  var vm = this;

  var watcher = $scope.$watch('textBox', function(newVal) {
    if(newVal) {
      vm.textBox = newVal;
      watcher();
    }
  });
}

. .

+2

controllerAs, ( , ). , :

    function exampleDirective() {
        return {            
            require: '^testBox',
            link: function (scope, element, attrs, testBox) {
                scope.example.testBox = testBox;
            },
            controllerAs: 'example',
            controller: function() {
                // silly example, but you get the idea!
                this.user = this.testBox.user;
            }
        }
    };
0

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


All Articles