我正在尝试添加一个body指令,该指令将具有一个左面板和一个右面板。但是在这些面板之间,我将有一些body指令专有的内容。我目前正在使用transclude = true选项加载内容。但是,我正在寻找一种使用两个ng-transclude的方法。我研究了很多解决方法,但是找不到理想的解决方案。我必须在body指令的编译步骤中手动添加已包含的对象。以下是我解决该问题的方法:
身体指令
var myApp = angular.module('myApp', []);
myApp.directive('body', function () {
return {
restrict: 'A',
transclude: true,
scope: {
title: '@'
},
templateUrl: 'body.html',
compile: function compile(element, attrs, transclude) {
return function (scope) {
transclude(scope.$parent, function (clone) {
for (var i = 0; i < clone.length; i++){
var el = $(clone[i]);
if(el.attr('panel-left') !== undefined) {
element.find('#firstPanel').html(el);
} else if(el.attr('panel-right') !== undefined) {
element.find('#secondPanel').html(el);
}
}
});
}
}
};
});
myApp.directive('panelLeft', function () {
return {
require: "^body",
restrict: 'A',
transclude: true,
replace: true,
template: '<div ng-transclude></div>'
};
});
myApp.directive('panelRight', function () {
return {
require: "^body",
restrict: 'A',
transclude: true,
replace: true,
template: '<div ng-transclude></div>'
};
});
模板
<script type="text/ng-template" id="body.html">
<h1> {{title}} </h1>
<hr/>
<div id="firstPanel" class="inner-panel"></div>
<div id="innerMiddleContent" class="inner-panel">middle private content here</div>
<div id="secondPanel" class="inner-panel"></div>
</script>
<div body title="Sample Body Directive">
<div panel-left>
Public content that goes on the left
</div>
<div panel-right>
Public content that goes on the right
</div>
</div>
这是此示例的JSFiddle。我正在寻找这样的东西:
必备模板
<script type="text/ng-template" id="body.html">
<h1> {{title}} </h1>
<hr/>
<div id="firstPanel" class="inner-panel" ng-transclude="panel-left"></div>
<div id="innerMiddleContent" class="inner-panel">middle private content here</div>
<div id="secondPanel" class="inner-panel" ng-transclude="panel-right"></div>
</script>
问题:我做错什么了吗?是否有解决此问题的推荐方法?
您看过此指令吗?
https://github.com/zachsnow/ng-multi-transclude
我认为这正是您想要的。
因此,只需对模板进行一些修改
<div ng-multi-transclude="panel-left" class="inner-panel"></div>
<div ng-multi-transclude="panel-right" class="inner-panel">middle private content here</div>
<div id="secondPanel" class="inner-panel"></div>
然后你可以像这样使用它
<div body title="Sample Body Directive">
<div name="panel-left">
Public content that goes on the left
</div>
<div name="panel-right">
Public content that goes on the right
</div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句