In the directive we add a new scope variable 'confirmPositive' with the '&' binding to allow our controller to assign a function to it. When the OK button is pressed, this function will be called. In the template we add another button - the cancel button will retain the alert behaviour and just hide the dialog whereas the OK button will call a function which hides the dialog and then calls the confirmPositive function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.directive('myConfirm', function () { | |
function link($scope) { | |
$scope.visible = false; | |
$scope.posClick = function() { | |
$scope.visible = false; | |
$scope.confirmPositive(); | |
}; | |
} | |
return { | |
template: '<div class="mydialog-bg" ng-show="visible"><div class="mydialog-pop"><div class="mydialog-title">{{confirmTitle}}</div><div>{{confirmContent}}</div><input type="button" ng-click="posClick()" value="OK" /><input type="button" ng-click="visible=false" value="Cancel" /></div></div>', | |
link: link, | |
scope: { | |
confirmTitle: '@', | |
confirmContent: '@', | |
confirmPositive: '&', | |
visible: '=' | |
} | |
}; | |
}) |
In the controller we just need to add the function which will carry out our destructive action when the user clicks OK.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.controller('myCtl', function ($scope) { | |
$scope.showConfirm = function() { | |
$scope.confirmMessage = 'Are you sure you want to?'; | |
$scope.confirmVisible = true; | |
}; | |
$scope.doThing = function() { | |
console.log('do something that requires confirmation'); | |
}; | |
}) |
In our HTML we just need to add an attribute so that the function in our controller is passed to our directive.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<body ng-controller="myCtl"> | |
<input type="button" ng-click="showConfirm()" value="Show" /> | |
<div my-confirm visible="confirmVisible" confirm-content="{{confirmMessage}}" confirm-title="Confirm Dialog Demo" confirm-positive="doThing()"></div> | |
</body> |
A complete example can be found here.