javascript-角度的包含和范围:为什么这不起作用?
作者:互联网
我有一个非常简单的设置:
<pane title="mytitle">Title in parent (transcluded): {{title}}</pane>
和
angular.module('transclude', [])
.directive('pane', function(){
return {
restrict: 'E',
transclude: true,
scope: { title:'@' },
template: '<div>' +
'<div>Title in isolated scope: {{title}}</div>' +
'<div ng-transclude></div>' +
'</div>'
};
});
pl子在这里:http://plnkr.co/edit/yRHcNGjQAq1NHDTuwXku
包含本身是有效的,但是{{title}}仅在指令的模板中被替换.
但是,即使伪指令在其作用域内具有可变的标题,但被包含在元素内的{{title}}仍为空.这是为什么?
解决方法:
被包含的元素的范围不是指令的子范围,而是同级的子范围.这就是文档所说的:
In a typical setup the widget creates an isolate scope, but the transclusion is not a child, but a sibling of the isolate scope.
在这种情况下,最简单的解决方案如下:
.directive('pane', function () {
return {
restrict: 'E',
transclude: true,
scope: {
title: '@'
},
template:
'<div>' +
'<div>Title in isolated scope: {{title}}</div>' +
'<div ng-transclude></div>' +
'</div>',
link: function (scope, element, attrs) {
scope.$$nextSibling.title = attrs.title;
}
};
});
演示:http://plnkr.co/edit/ouq9B4F2qFPh557708Q1?p=preview
标签:transclusion,javascript,angularjs,angularjs-scope 来源: https://codeday.me/bug/20191012/1900469.html