我正在尝试弄清楚如何通过嵌套指令向下传递包含并绑定(bind)到最内层指令中的数据。将它想象成一个列表类型控件,您可以将它绑定(bind)到一个数据列表,而嵌入是您要用来显示数据的模板。这是一个仅绑定(bind)到单个值的基本示例(这里是一个 plunk)。
html
<body ng-app="myApp" ng-controller="AppCtrl as app">
<outer model="app.data"><div>{{ source.name }}</div></outer>
</body>
JavaScript
angular.module('myApp', [])
.controller('AppCtrl', [function() {
var ctrl = this;
ctrl.data = { name: "Han Solo" };
ctrl.welcomeMessage = 'Welcome to Angular';
}])
.directive('outer', function(){
return {
restrict: 'E',
transclude: true,
scope: {
model: '='
},
template: '<div class="outer"><inner my-data="model"><div ng-transclude></div></div></div>'
};
})
.directive('inner', function(){
return {
restrict: 'E',
transclude: true,
scope: {
source: '=myData'
},
template :'<div class="inner" my-transclude></div>'
};
})
.directive('myTransclude', function() {
return {
restrict: 'A',
transclude: 'element',
link: function(scope, element, attrs, controller, transclude) {
transclude(scope, function(clone) {
element.after(clone);
})
}
}
});
如您所见,嵌入的位没有出现。有什么想法吗?
最佳答案
在这种情况下,您不必使用自定义 transclude 指令或任何技巧。我在您的代码中发现的问题是默认情况下 transclude 被编译到父范围。因此,您可以通过实现指令的 compile
阶段来解决这个问题(这发生在链接阶段之前)。实现看起来像下面的代码:
app.directive('inner', function () {
return {
restrict: 'E',
transclude: true,
scope: {
source: '=myData'
},
template: '<div class="inner" ng-transclude></div>',
compile: function (tElem, tAttrs, transclude) {
return function (scope, elem, attrs) { // link
transclude(scope, function (clone) {
elem.children('.inner').append(clone);
});
};
}
};
});
通过这样做,您强制您的指令对其隔离范围进行嵌入。
关于javascript - 如何通过 Angular 中的嵌套指令向下传递包含?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40098437/