Skip to content

Instantly share code, notes, and snippets.

@DevankAgarwal
Last active October 9, 2015 10:39
Show Gist options
  • Save DevankAgarwal/286f1e6be5681f78e689 to your computer and use it in GitHub Desktop.
Save DevankAgarwal/286f1e6be5681f78e689 to your computer and use it in GitHub Desktop.
Modal window in angular
(function () {
'use strict';
angular
.module(<moduleName>)
.factory('modalService', modalService);
/* @ngInject */
function modalService($q, $modal) {
var service = {
openModal: openModal,
showModal: showModal,
getModal: getModal,
},
code:{},
return service;
////////////////
//code => code can be the key which refers to a template url,
//code => code can also be templateUrl,
//data => data can be any thing(string, json, numeric) which can be passed to the respective modal controller
//scope => scope will be send only when the modal has to be created in the same scope.default rootScope.
function openModal(code, data, scope) {
var deferred = $q.defer(),
modalScope = angular.isDefined(scope) ? scope : $rootScope,
modal = angular.isDefined(codes[code]) ? getModal(codes[code], modalScope) : getModal(code, modalScope);
modal.$scope.data = angular.isDefined(data) ? data : {};
modal.$scope.$on('modal.hide', function () {
if (modal.$scope.result) {
deferred.resolve({
code: code,
result: modal.$scope.result
});
} else {
deferred.reject({
code: code,
reason: 'hidden'
});
}
});
modal.$scope.$on('modal.show', function () {});
modal.$promise.then(modal.show);
return deferred.promise;
}
//////////////////////////////////////////////////
// templateUrl is compulsary..
// scope if not sent rootScope will be taken.
function getModal(templateUrl, scope) {
var modal = $modal({
template: templateUrl,
scope: angular.isDefined(scope) ? scope.$new() : $rootScope.$new(),
placement: 'center',
backdrop: 'static',
size: 'lg',
show: false
});
modal.$scope.$on('closeModals', function () {
modal.$scope.$hide();
});
return modal;
}
////////////////
//code => code can be the key which refers to a template url,
//code => code can also be templateUrl,
//data => data can be any thing(string, json, numeric) which can be passed to the respective modal controller
//scope => scope will be send only when the modal has to be created in the same scope.default rootScope.
function showModal(code, data, scope) {
var modalScope = angular.isDefined(scope) ? scope : $rootScope,
modal = angular.isDefined(codes[code]) ? getModal(codes[code], modalScope) : getModal(code, modalScope);
modal.$scope.data = data;
modal.$promise.then(modal.show);
return modal;
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment