我有三个指令:
aiOutter,aiMiddle和aiInner。
app.directive('aiOutter', function() {
return {
restrict: 'A',
scope: {
data: '='
},
template: '<div>Outter: {{data}}</div>',
transclude: true,
link: function(scope, elem, attrs) {
console.log('outter recognized');
return console.log('outter data:', scope.data);
}
};
}).directive('aiMiddle', function() {
return {
restrict: 'A',
scope: {
data: '='
},
template: '<div>Middle: {{data}}</div>',
transclude: true,
link: function(scope, elem, attrs) {
console.log('middle recognized');
return console.log('middle data:', scope.data);
}
};
}).directive('aiInner', function() {
return {
restrict: 'A',
scope: {
data: '='
},
template: '<div>Inner: {{data}}</div>',
link: function(scope, elem, attrs) {
console.log('inner recognized');
console.log('inner data:', scope.data);
scope.changeData = function(newData) {
scope.data = newData;
}
}
};
});
我的标记如下所示:
<body ng-controller="MainCtrl">
<div ai-outter data="name">
<div ai-middle data="data">
<div ai-inner data="data">
</div>
</div>
</div>
只有最外面的指令似乎被接受了。我需要做什么才能使用此继承模式,以及能够使用transcluded标记填充最内层指令?
Plunker:http://plnkr.co/edit/HvaJKmGH2agEOKHGrZvV
编辑澄清
我根据PascalPrecht的建议编辑了我的标记(更新的plunker在这里:http://plnkr.co/edit/HvaJKmGH2agEOKHGrZvV)
<body ng-controller="MainCtrl">
<div ai-outter data="name" ng-transclude>
<div ai-middle data="name" ng-transclude>
<div ai-inner data="name" ng-transclude>
<h1> Hello, {{name}}</h1>
<button ng-click="name = 'bob'">Click me</button>
</div>
</div>
</div>
但是,我认为我遇到了一个范围问题。当我按下按钮时,{{name}}模型应该一直绑定,如果没有的话?目前,只有最内部的范围正在更新。
我认为我对指令的范围很困惑。
答案 0 :(得分:1)
您不能使用原始值,您应该引用示波器控制器中的对象。
查看代码的修改版本: http://plnkr.co/edit/666Adad72zRJIasOzurs?p=preview
请务必查看以下优秀答案: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
答案 1 :(得分:0)
您需要在指令模板中指定ng-transclude
以告知角度,在何处放置已转换的内容。然后,您可以通过提供获取被转换内容的模板来进行链接,其中被转换的内容再次包含获取双向绑定数据的指令。
我相应地更新了你的插件:http://plnkr.co/edit/sM3Jnj?p=preview