Модальное подтверждение как директива UI Angular
Я пытаюсь сделать директиву Angular с angular -bootstrap, чтобы имитировать функцию confirm().
Вот фрагмент, показывающий визуальный результат и поведение, которые я хочу достичь: http://embed.plnkr.co/27fBNbHmxx144ptrCuXV/preview
Теперь я хотел бы использовать директиву для вызова модального окна:
<div ng-controller="ModalDemoCtrl">
<ul>
<li ng-repeat="item in items">
{{ item }} <a ng-really-message="Are you sure ?" ng-really-click="reallyDelete(item)">Delete</a>
</li>
</ul>
</div>
Я создал рабочую директиву, которая использует функцию "confirm()", но когда я пытаюсь использовать модальное окно вместо функции подтверждения, я получаю ошибку "$digest already in progress
".
Плунк: http://plnkr.co/edit/JSOInyZIvMtBZFaNvQRO?p=preview
var ModalDemoCtrl = function($scope, $modal) {
$scope.items = ['item1', 'item2', 'item3'];
$scope.reallyDelete = function(item) {
$scope.items = window._.remove($scope.items, function(elem) {
return elem != item;
});
};
};
angular.module('ngReallyClickModule', ['ui.bootstrap'])
.directive('ngReallyClick', ['$modal',
function($modal) {
var ModalInstanceCtrl = function($scope, $modalInstance) {
$scope.ok = function() {
$modalInstance.close();
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('click', function() {
var message = attrs.ngReallyMessage || "Are you sure ?";
/*
//This works
if (message && confirm(message)) {
scope.$apply(attrs.ngReallyClick);
}
//*/
//*This doesn't work
var modalHtml = '<div class="modal-body">' + message + '</div>';
modalHtml += '<div class="modal-footer"><button class="btn btn-primary" ng-click="ok()">OK</button><button class="btn btn-warning" ng-click="cancel()">Cancel</button></div>';
var modalInstance = $modal.open({
template: modalHtml,
controller: ModalInstanceCtrl
});
modalInstance.result.then(function() {
scope.$apply(attrs.ngReallyClick); //raise an error : $digest already in progress
}, function() {
//Modal dismissed
});
//*/
});
}
}
}
]);
I
Ответы
Ответ 1
Попробуйте привязку к функции (&
):
scope:{
ngReallyClick:"&", //declare a function binding for directive
item:"=" //the current item for the directive
},
Ваш html:
<a ng-really-message="Are you sure ?" ng-really-click="reallyDelete(item)" item="item">Delete</a>
Вызовите свою функцию, когда пользователь нажимает ok:
modalInstance.result.then(function() {
scope.ngReallyClick({item:scope.item}); //call the function though function binding
}, function() {
//Modal dismissed
});
DEMO