2

How can I access a directive's ngModelController from another directive?

The scenario

I'm creating a type ahead widget, which is composed of a typeAhead directive and autoCompletePopUp directive. AutoCompletePopUp directive will interact with the typeAhead using typeAhead's controller.

But I don't know how to call typeAhead's $setViewValue from autoCompletePopUp when an item is selected.

Bhoomtawath Plinsut
  • 1,337
  • 1
  • 16
  • 31
  • 2
    These helped me a lot on this topic: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController, http://stackoverflow.com/questions/15622863/angularjs-directive-controllers-requiring-parent-directive-controllers – TrazeK Aug 13 '14 at 05:14
  • @TrazeK Thank you, didn't know that nested directive share the same isolated scope. – Bhoomtawath Plinsut Aug 13 '14 at 06:15
  • No worries. A lot of us didn't know ;) – TrazeK Aug 13 '14 at 06:42

1 Answers1

0

Why not just add a function to the controller for typeAhead that calls $setViewValue on itself. In the context of typeAhead's controller you should have access to the scope. You can put the ngModelController for typeAhead on the scope if needed. Something like this:

angular.module("myModule").directive("typeAhead", function() {
   return {
      require: "ngModel",
      controller: function($scope) {
         this.setValue = function(value) {
            $scope.ngModelController.$setViewValue(value);
         };
      },
      link: function(scope, element, attributes, ngModelController) {
         scope.ngModelController = ngModelController;
      },
   };
});

angular.module("myModule").directive("typeAhead", function() {
   return {
      require: "typeAhead",
      link: function(scope, element, attributes, typeAheadController) {
         scope.someAction = function(value) {
            typeAheadController.setValue(value);
         };
      },
   };
});

(protect against minification and move controllers into separate objects / files as desired; done inline here for convenience)

Josh G
  • 14,068
  • 7
  • 62
  • 74