I have a button on my webpage. If I click on that button, Modal Dialog is opened on which 2 buttons(OK & Cancel) are there. I want my web page to be operated without mouse. So when Modal Dialog is opened, automatically. The focus should be set on OK button. When dialog is closed, focus should be set on original button on web page. My code is as below. When I am clicking on Open button for the 1st time, focus is set on OK button. But when I am closing the modal and reopening it, it is not getting set on OK button.
$scope.OpenModal = function() {
//Popup the Modal Dialog Box
$scope.modalTitle = "Confirm?";
$scope.note=null;
$scope.modalShown = !$scope.modalShown;
$scope.focusInput=true;
$scope.ok = function () {
$scope.Message = "Confirmed";
_clearSKUFormOnConfirm();
$scope.modalShown = false;
$scope.focusInput = true;
}
$scope.cancel = function () {
$scope.Message = "Cancelled";
_clearSKUFormOnCancle();
$scope.modalShown = false;
$scope.focusInput = true;
}
}
app.directive('modalDialog', function() {
return {
restrict: 'E',
scope: {
show: '='
},
replace: true, // Replace with the template below
transclude: true, // we want to insert custom content inside the directive
link: function(scope, element, attrs) {
scope.dialogStyle = {};
if (attrs.width)
scope.dialogStyle.width = attrs.width;
if (attrs.height)
scope.dialogStyle.height = attrs.height;
scope.hideModal = function() {
scope.show = false;
};
},
template: "<div class='ng-modal' ng-show='show'><div class='ng-modal-overlay'></div><div class='ng-modal-dialog' ng-style='dialogStyle'><div class='ng-modal-close close' ng-click='hideModal()'>x</div><div class='ng-modal-dialog-content' ng-transclude></div></div></div>"
};
});
app.directive('focusMe', function($timeout, $parse) {
return {
link: function(scope, element, attrs) {
var model = $parse(attrs.focusMe);
scope.$watch(model, function(value) {
console.log('value=',value);
if(value === true) {
$timeout(function() {
element[0].focus();
}, 20);
}
});
element.bind('blur', function() {
console.log('blur')
scope.$apply(model.assign(scope, false));
})
}
};
});
<button ng-click="OpenModal()" ng-disabled="isValid"
role="button" >
<span class="fa fa-ban"></span> Open
</button>
<modal-dialog show='modalShown' width='440px'>
<div class="modal-header">
<h5 class="modal-title">{{modalTitle}}</h5>
</div>
<div class="modal-body">
<p>{{modalMessage}} </p>
</div>
<div class="modal-footer">
<button ng-click="ok()" focus-me="true" >OK</button>
<button ng-click="cancel()">Cancel</button>
</div>
</modal-dialog>