0

I have a directive that includes another one.

The child directive is used widely throughout my application, while the parent one is just used in one place.

I would like to add a binding to the child directive's input element. However, this binding would be necessary only when the directive is placed within the parent, not if it is used as a standalone.

Now i wonder about the best way to do this.

I thought about cycling the child nodes of my parent directive until i reach the input, then bind to it. However, this will lead to a confusing, neboulous process like this one:

 $element.find('suggestion').childNodes[0].childNodes[1] // ... and so on

If i try to find the input directly, i get an empty object.

Is this the way to go or am I unaware of a better method?

user2422960
  • 1,476
  • 6
  • 16
  • 28

1 Answers1

0

The general approach to this is to use the controller of your parent directive and add 'suggestion' to the scope. Angular binds your child directive via ng-model='suggestion'.

Your parent directive would be something like this:

angular.module('yourappname').directive('parentdirective',function(){
   return {
      .....
      controller: 'ParentCtrl',
      .....
   }
}

Your controller:

angular.module('controller', function($scope){
   $scope.suggestion // note that setting primitives directly on the scope is not recommended
 }

Your child directive:

<input ... ng-model="suggestion" />
Walter Brand
  • 679
  • 3
  • 9
  • I can't see how i could do that, as the suggestion directive is using an isolated scope – user2422960 Mar 31 '14 at 07:36
  • Like I said, this would be the general approach to it. If you share your code (via Plunker), I could give you a answer taylored to your situation – Walter Brand Mar 31 '14 at 07:41
  • You can call from the child directive a method on the parent directive. So you could do one method where the child directive add itself to an array on the parent, and a second method that does the binding. I gave an exemple here : http://stackoverflow.com/questions/22620949/angularjs-list-of-toggle-buttons-directive/22641820#22641820 – Olivvv Apr 02 '14 at 13:19