我有一个相当复杂的模态对话框指令,其中包含一些子指令,转换,隔离范围。以下是它的外观示例:
<dm-modal reference="previewDialog" additional-class="datasourcePreview">
<dm-modal-header><div class="dialog-title" ng-controller="dsPreviewCtrl">Preview of {{previewData.dataSourceName}}</div> </dm-modal-header>
<dm-modal-body>
<div ng-controller="dsPreviewCtrl" ng-include="dsPreview.html'" ></div>
</dm-modal-body>
<dm-modal-footer>
Choose one
</dm-modal-footer>
<dm-modal-footer-buttons>
<dm-modal-footer-button type="done" ng-click="doSomething()"></dm-modal-footer-button>
<dm-modal-footer-button type="delete"></dm-modal-footer-button>
</dm-modal-footer-buttons>
</dm-modal>
当使用这个指令时,80%以上的时间我只需要摆弄几个东西,因为它只是一个确认对话框,其余的选项都是标准的。我不想看到如上所述的毛茸茸的界面,而是想实现一个如下所示的指令,但最终只是生成上面的指令。
<dm-simple-modal reference="confirmDialog" title="Are you sure?" okClick="handleOk()">
<div ng-controller="dsPreviewCtrl" ng-include="'dsPreview.html'"></div>
</dm-simple-modal>
因此,基本上将上述标记转换为另一个“更完整”指令的完整标记对我来说似乎是最简单的,如下所示:
<dm-modal reference="confirmDialog">
<dm-modal-header>
Are you sure?
</dm-modal-header>
<dm-modal-body>
<div ng-controller="dsPreviewCtrl" ng-include="'dsPreview.html'"></div>
</dm-modal-body>
<dm-modal-footer-buttons>
<dm-modal-footer-button text="Yes" ng-click="handleOk()"></dm-modal-footer-button>
<dm-modal-footer-button type="No"></dm-modal-footer-button>
</dm-modal-footer-buttons>
</dm-modal>
然后angular会将这个指令编译成工作的html。
将这个问题变成一个更人为但更简单的例子,我创造了一个小提琴http://jsfiddle.net/josepheames/JEYJa/1/
我甚至试图在更复杂的指令之后使用模板制作更简单的指令,但我无法使其工作。
这个小提琴中的指令看起来像这样:
<div ng-controller="MyCtrl" ng-click="doClick()">
<complex-directive handle="complexDir" titleColor="blue">
<h1>{{title}}</h1>
</complex-directive>
<simple-directive handle="simpleDir" title="another {{title}}" color="red" />
</div>
工作复杂指令是这样的:
myApp.directive('complexDirective', function() {
return {
restrict: 'E',
scope: {
handle: '='
},
replace: true,
transclude: true,
template: '<div ng-transclude></div>',
link: function(scope, element, attr) {
scope.handle= {
doSomething: function() {
element.css('background-color', attr.titlecolor);
}
}
}
}
});
我对一个简单指令的失败尝试是这样的:
myApp.directive('simpleDirective', function() {
return {
restrict: 'E',
scope: {
handle: '='
},
replace: true,
transclude: true,
template: '<complex-directive handle="{{thehandle}}" titleColor="{{color}}"><h1>{{title}}</h1></complex-directive>',
link: function(scope, element, attr) {
scope.thehandle = attr.handle,
scope.color = attr.titlecolor,
scope.title = element.html(),
scope.handle= {
doSomething: function() {
element.css('background-color', attr.titlecolor);
}
}
}
}
});