Here's one way to trigger a custom alert dialog from a controller.
To achieve this we create an AngularJS directive which, when activated, will cover the screen with a full-screen translucent element with a child element which will be our pop-up dialog.
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('myAlert', function () { | |
return { | |
template: '<div class="mydialog-bg" ng-show="visible"><div class="mydialog-pop"><div class="mydialog-title">{{alertTitle}}</div><div>{{alertContent}}</div><input type="button" ng-click="visible=false" value="OK" /></div></div>', | |
link: function(scope) { scope.visible = false;}, | |
scope: { | |
alertTitle: '@', | |
alertContent: '@', | |
visible: '=' | |
} | |
}; | |
}) |
We have a simple template with the full-screen background and a dialog with title, content and an OK button. When the button is clicked, visible is set to false. A link function initialises the visible variable to false and we set up some variables so that the title and content can be set and a variable mapped to the visible variable.
In our controller we can create a function to show our alert. In this example, when a button is clicked, we will set our alert message and show the alert:
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.showAlert = function() { | |
$scope.alertMessage = 'This is my alert message!'; | |
$scope.alertVisible = true; | |
} | |
}) |
The HTML including our alert directive looks like this:
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="showAlert()" value="Show" /> | |
<div my-alert visible="alertVisible" alert-content="{{alertMessage}}" alert-title="Alert Dialog Demo"></div> | |
</body> |
A complete example can be found here.
No comments:
Post a Comment