0

I need get 'c' attribute inside child element from parent (see in jsfiddle) Is it possible?

<div ng-app="myApp">
    <box c="yellow">
       <item>item</item>
    </box>
</div>    

angular.module('myApp', [])
.directive('box', function() {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        template: '<div ng-transclude></div>'
    };
})
.directive('item', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {c:'='},
        template: '<div>c:{{c}}</div>'
    };
});
vinnitu
  • 4,234
  • 10
  • 41
  • 59

2 Answers2

2

Since your item directive defines an isolate scope, you need to define an attribute on item for each scope property you want. So at a minimum you'll need:

<item c="c">item</item>

Now, the c to the right of the = needs to be a scope property on the box directive, so create a linking function to make that happen:

link: function(scope, element, attrs) {
    scope.c = attrs.c;
}

Fiddle.

Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
0

When you use translcude, the parent dom object is not actually a parent in scopes-tree. Nice scope inheritance description here:

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

You can get it directly, but it is not a beautiful way:

var app = angular.module('plunker', []);

app.directive('box', function(){
     return {
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: { c: '@' },
        template: '<div ng-transclude></div>'
    };
});

app.directive('item', function(){
  return {
      restrict: 'E',
      replace: true,
      template: '<div>c:{{$parent.$$prevSibling.c}}</div>'
  };
});

Example: http://plnkr.co/edit/YuYry9?p=preview

I believe there are more ng-like ways of doing that...

Community
  • 1
  • 1
Pythonic
  • 486
  • 5
  • 9