angular中transclude和scope之间的关系

本文探讨了AngularJS中指令的使用方式及其如何与作用域交互。特别关注了transclude功能,展示了如何根据不同需求选择性地使用父作用域或子作用域。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接上代码


app.controller('MainCtrl', function($scope) {
$scope.person = {
name: 'John Doe',
profession: 'Fake name'
};

$scope.header = 'Person';
});

app.directive('person', function() {
return {
restrict: 'EA',
scope: {
header: '='
},
transclude:true,
template: '<div ng-transclude></div>',
link: function(scope, element, attrs) {
scope.person = {
name: 'Directive Joe',
profession: 'Scope guy'
};

scope.header = 'Directive\'s header';
}
};
});



<body ng-controller="MainCtrl">
<person header="header">
<h2>{{header}}</h2>
<p>Hello, I am {{person.name}} and,</p>
<p>I am a {{person.profession}}</p>
</person>
</body>

以上代码会变成

<body ng-controller="MainCtrl" class="ng-scope">
<person header="header" class="ng-isolate-scope"><div ng-transclude="">
<h2 class="ng-scope ng-binding">Directive's header</h2>
<p class="ng-scope ng-binding">Hello, I am John Doe and,</p>
<p class="ng-scope ng-binding">I am a Fake name</p>
</div></person>
</body>

即原有的属性不会被替换,而原来没有的属性,则会使用新的

如果想通过指令来控制接受父级的scope值还是子集的scope值,可以通过如下代码区分

app.directive('person', function() {
return {
restrict: 'EA',
scope: {
header: '='
},
transclude:true,
link: function(scope, element, attrs, ctrl, transclude) {
scope.person = {
name: 'Directive Joe',
profession: 'Scope guy'
};

scope.header = 'Directive\'s header';
transclude(scope.$parent, function(clone, scope) {
element.append(clone);
});
}
};
});



app.directive('person', function() {
return {
restrict: 'EA',
scope: {
header: '='
},
transclude:true,
link: function(scope, element, attrs, ctrl, transclude) {
scope.person = {
name: 'Directive Joe',
profession: 'Scope guy'
};

scope.header = 'Directive\'s header';
transclude(scope, function(clone, scope) {
element.append(clone);
});
}
};
});

以上两组代码中,transclude传递的参数中,第一个参数分别传递的为scope.$parent和scope

参考自
http://angular-tips.com/blog/2014/03/transclusion-and-scopes/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值