Угловое преобразование в директиву, содержащую ng-шаблон (универсальный Confirm Modal)
Здравствуйте, я изо всех сил пытаюсь создать общую директиву подтверждения, основанную на модальной директиве angular-bootstrap.
Я не могу найти способ включить мой контент в ng-шаблон, используемый для модальной конструкции, потому что ng-transclude
директива не оценивается, так как она является частью ng-template
загружен позже при выполнении $modal.open()
:
index.html (вставка директивы):
<confirm-popup
is-open="openConfirmation"
on-confirm="onPopupConfirmed()"
on-cancel="onPopupCanceled()"
>
Are you sure ? (modal #{{index}})
verifyPopup.html (шаблон директивы):
<script type="text/ng-template" id="confirmModalTemplate.html">
<div>
<div class="modal-header">
<h3>Confirm ?</h3>
</div>
<div class="modal-body">
{{directiveTranscludedContent}} // ng-transclude do not work here
</div>
<div class="modal-footer">
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
<button class="btn btn-primary" ng-click="ok()">Validate</button>
</div>
</div>
</script>
verifyPopup.js (директива JS):
.directive('confirmPopup', [
function() {
return {
templateUrl: 'confirmPopup.html',
restrict: 'EA',
replace: true,
transclude: true,
scope: {
isOpen: '=',
confirm: "&onConfirm",
cancel: "&onCancel"
},
controller: ['$scope', '$element', '$modal', '$transclude', '$compile', function($scope, $element, $modal, $transclude, $compile) {
// watching isOpen attribute to dispay modal when needed
$scope.$watch(
function() {
return $scope.isOpen;
},
function(newValue) {
if (newValue === true) {
openModal();
} else {
// if a modal is already dispayed : the modal must be canceled/confirmed by the user
// else (if no modal is dispayed), then do nothing
}
}
);
// open modal function
// create / register ok/cancel callbacks
// and open modal
// all on one shot
function openModal() {
$modal.open({
templateUrl: 'confirmModalTemplate.html',
controller: ['$scope', '$modalInstance', 'content', function($scope, $modalInstance, content) {
$scope.directiveTranscludedContent = content;
$scope.ok = function() {
$modalInstance.close();
};
$scope.cancel = function() {
$modalInstance.dismiss();
};
}],
resolve: {
content: function() {
return $transclude().html();
//return $compile($transclude().contents())($scope);
},
}
})
.result.then(
// modal has been validated
function() {
$scope.confirm();
},
// modal has been dismissed
function() {
if ($scope.cancel) {
$scope.cancel();
}
}
);
};
}]
};
}
]);
Если это не достаточно ясно, посмотрите этот PLUNKER, где я жду, чтобы увидеть "Are you sure ? (modal #2)
"только при нажатии на"open confirm modal #2
кнопка.
1 ответ
ui-bootstrap модальный поддерживает только template
или же templateUrl
как способ указать содержание. Однако содержимое извлекается, оно компилируется и связывается с предоставленной областью $modal
(точнее, внутренний $modalStack
) оказание услуг.
Так что, по крайней мере, так нет способа обеспечить включение.
Одним из способов решения этой проблемы было бы внедрение директивы-заполнителя, которая добавляла бы включенный DOM - но включенный DOM, поскольку он приходит из местоположения, отличного от модального, нужно каким-то образом передать этой директиве-заполнителю. У вас уже есть content
в качестве введенного параметра разрешения. Я буду использовать это с небольшими изменениями - я передам реальный DOM, а не разобранный HTML.
Итак, на высоком уровне:
.directive("confirmPopupTransclude", function($parse){
return {
link: function(scope, element, attrs){
// could have been done with "=" and isolate scope,
// but avoids an unnecessary $watch
var templateAttr = attrs.confirmPopupTransclude;
var actualTemplateDOM = $parse(templateAttr)(scope);
element.append(actualTemplateDOM);
}
};
})
И в openModal
функция (без учета несвязанных свойств):
function openModal{
$modal.open({
controller: function($scope, content){
$scope.template = content;
// etc...
},
resolve: {
content: function(){
var transcludedContent;
$transclude(function(clone){
transcludedContent = clone;
});
return transcludedContent; // actual linked DOM
},
// etc...
}
Наконец, в фактическом шаблоне для модального:
<div class="modal-body">
<div confirm-popup-transclude="template"></div>
</div>