I encountered a problem with my requirement. I need a confirm box to appear when the user attempts to navigate to the next state/page. Only if the user clicks on the "Ok" button should it proceed to the next state; otherwise, it should stay as it is. Below is an explanation of my code.
<li ui-sref-active="active" ><a ui-sref=".profile" confirm="Are you sure to move into the next page?">Profile</a></li>
<li ui-sref-active="active"><a ui-sref=".dept" >Department</a></li>
For example, if the user clicked on the profile menu, a confirm box will appear first, and upon pressing Ok, it will proceed.
dashboard.directive('confirm', function(ConfirmService, $state) {
return {
restrict: 'A',
scope: {
eventHandler: '&ngClick'
},
link: function(scope, element, attrs){
element.unbind("click");
element.bind("click", function(e) {
e.preventDefault(); // block the href generated by ui-sref
ConfirmService.open(attrs.confirm, $state.go(attrs.uiSref)); // pass ui-sref into $state.go
});
}
}
});
dashboard.service('ConfirmService', function($uibModal) {
var service = {};
service.open = function (text, onOk) {
var modalInstance = $uibModal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalConfirmCtrl',
resolve: {
text: function () {
return text;
}
}
});
modalInstance.result.then(function (selectedItem) {
onOk();
}, function () {
});
};
return service;
})
dashboard.controller('ModalConfirmCtrl', function ($scope, $uibModalInstance, text) {
$scope.text = text;
$scope.ok = function () {
$uibModalInstance.close(true);
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
});
Updated JavaScript Code
dashboard.directive('confirm', function($uibModal, $state,$timeout) {
return {
restrict: 'A',
scope: {
eventHandler: '&ngClick'
},
link: function(scope, element, attrs){
var isConfirmed = false;
element.bind("click", function (e) {
if (!isConfirmed) {
e.preventDefault();
$uibModal.open({
templateUrl: 'myModalContent.html',
controller: function ($scope, $uibModalInstance) {
//$scope.text=text;
$scope.ok = function () { $uibModalInstance.close(); }
$scope.cancel = function () { $uibModalInstance.dismiss(); }
}
})
.result.then(function () {
isConfirmed = true;
$timeout(function () {
element.click();
});
});
}
});
}
}
});
In this version, the confirm box still appears, but the issue is that it moves to the profile state first before showing the confirm box. I want the confirm box to display before navigating to the next state, and only after pressing Ok, it should proceed. I tried using ng-click
, but it misses the active
class and cursor:pointer
property on the menu. Any assistance in resolving this issue would be greatly appreciated.