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

2 回答 2

2

由于您的 item 指令定义了一个隔离范围,因此您需要为所需的每个范围属性在 item 上定义一个属性。所以至少你需要:

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

现在,c右边的=需要是 box 指令的范围属性,所以创建一个链接函数来实现它:

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

小提琴

于 2013-02-11T22:38:00.283 回答
0

当你使用 translcude 时,父 dom 对象实际上并不是 scopes-tree 中的父对象。很好的范围继承描述在这里:

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 的方法可以做到这一点......

于 2013-02-11T12:27:43.357 回答