I have a simple modal dialog. I would like to convert this directive
is exposed globally
in the app.
for that, I understand i need to create a service
, but I don't know how to initiate the directive
from there.
and i would like to even over-write the width, height and titles.
here is the simple dialog code :
var app = angular.module('myApp', []);
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' ng-click='hideModal()'></div><div class='ng-modal-dialog' ng-style='dialogStyle'><div class='ng-modal-close' ng-click='hideModal()'>X</div><div class='ng-modal-dialog-content' ng-transclude></div></div></div>"
};
});
app.controller('MyCtrl', ['$scope', function($scope) {
$scope.modalShown = false;
$scope.toggleModal = function() {
$scope.modalShown = !$scope.modalShown;
};
}]);
mainly i am looking for re-usable, customizable, and on close i need to clear all data in the modal.
You must first understand, that when you create a directive it is globally accessible to your entire app. That is, you can use that directive in each and every page of your angular app module without any dependency injections.
Now the second question, you essentially will to make the height/width/content of the dialog configurable. Well, you guessed it right, Let's create a service and use it.
Create a service to hold the height/width/content of the dialog box.
app.service('modalService', function() { this.width = 100; this.height = 100; });
inject it in the directive
app.directive('modalDialog', function(modalService) { return { restrict: 'E', scope: { show: '=' }, replace: true, // Replace with the template below transclude: true, link: function(scope, element, attrs) { scope.dialogStyle = {}; if (modalService.width != 0) scope.dialogStyle.width = modalService.width; if (modalService.height != 0) scope.dialogStyle.height = modalService.height; scope.hideModal = function() { scope.show = false; modalService.modalContent = ''; }; }, template: "<div class='ng-modal' ng-show='show'><div class='ng-modal-overlay' ng-click='hideModal()'></div><div class='ng-modal-dialog' ng-style='dialogStyle'><div class='ng-modal-close' ng-click='hideModal()'>X</div><div class='ng-modal-dialog-content' ng-transclude></div></div></div>" }; });
Now reference this service in your controller and job's done.
You can find a demo here