Is it OK to use $$prevSibling to access scope data in a 'transcluded' directive?

angularjs, angularjs-directive, angularjs-scope

Solution

To avoid coupling your components together too much, I would avoid using `$$prevSibling`. The best solution since your `directiveB`-like components are expected to be used within `directiveA` components is to use `require`.

.directive( 'directiveB', function () {
  return {
    require: '^directiveA',
    scope: true,
    link: function ( scope, element, attrs, directiveA ) {
      scope.obj = directiveA.getObj();
    }
  };
})

The `^require` indicates that somewhere on the element of this directive or on any element above it in the DOM hierarchy is a directive called `directiveA`, and we want to call methods on its controller.

.directive( 'directiveA', function () {
  return {
    // ...
    controller: function ( $scope ) {
      // ...
      this.getObj = function () {
        return $scope.obj;
      };
    }
  };
})

So now in `directiveB` you can use `ng-model="obj.attr"`.

There are many variations on this, but considering how general the question was, I feel this is the best approach. Here's an updated Fiddle: http://jsfiddle.net/yugQf/7/.

Problem

My directive setup is as follows: ``` <div data-directive-a data-value="#33ff33" data-checked="true"> <div data-directive-b></div> </div> ``` - I'm using transclusion to ensure `directiveB` gets rendered. - `directiveA` has a checkbox that is meant to change some value whenever it is checked. - this value needs to be accessible in `directiveA` and `directiveB`'s scope. I've managed to do this, but only by referencing `$$prevSibling` - is there a better way? Here's the code: http://jsfiddle.net/janeklb/yugQf/ (in this sample, clicking the checkbox is simply meant to "clear" the value) -- A bit more depth: The 'contents' of `directiveA` (that which is being transcluded into it) isn't always `directiveB`. Other `directiveB`-like directives will end up in there as well. The `directiveB` "types" will always be used within `directiveA`.

Original source

Related problems