2013-02-11 93 views
0

我需要在父元素的子元素中获取“c”属性(请参阅jsfiddle) 是否有可能?如何绑定父级范围属性?

<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>' 
    }; 
}); 
+0

尝试覆盖链接函数和访问范围$ parent – 2013-02-11 12:23:58

回答

0

当您使用translcude时,父dom对象实际上并不是作用域树中的父对象。尼斯范围继承的描述在这里:

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

你可以直接得到它,但它不是一个美丽的方式:

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>' 
    }; 
}); 

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

我相信有更多的NG-像这样做的方法...

2

由于您的item指令定义了一个隔离范围,您需要定义一个属性o您需要的每个范围属性的n项。所以,至少你将需要:

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

现在,c到的=需要正确的是包装盒上的指令的作用域属性,因此创建一个链接功能来实现这一目标:

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

Fiddle