Error is raised when using modal service in angularjs - angularjs

[![enter image description here][1]][1]We are going to use modal delete confirmation in angularjs but there is a problem for using it and error "angular.js:15018 Error: [$templateRequest:tpload]" is raised, the ModalService is:
app.service("ModalService", ['$uibModal', function ($uibModal) {
var modalDefaults = {
backdrop: true,
keyboard: true,
modalFade: true,
templateUrl: "/app/modal.html"
};
var modalOptions = {
closeButtonText: 'Close',
actionButtonText: 'OK',
headerText: 'Proceed?',
bodyText: 'Perform this action?'
};
this.showModal = function (customModalDefaults, customModalOptions) {
if (!customModalDefaults) customModalDefaults = {};
customModalDefaults.backdrop = 'static';
return this.show(customModalDefaults, customModalOptions);
};
this.show = function (customModalDefaults, customModalOptions) {
//Create temp objects to work with since we're in a singleton service
var tempModalDefaults = {};
var tempModalOptions = {};
//Map angular-ui modal custom defaults to modal defaults defined in service
angular.extend(tempModalDefaults, modalDefaults, customModalDefaults);
//Map modal.html $scope custom properties to defaults defined in service
angular.extend(tempModalOptions, modalOptions, customModalOptions);
if (!tempModalDefaults.controller) {
tempModalDefaults.controller = function ($scope, $uibModalInstance) {
$scope.modalOptions = tempModalOptions;
$scope.modalOptions.ok = function (result) {
$uibModalInstance.close(result);
};
$scope.modalOptions.close = function (result) {
$uibModalInstance.dismiss('cancel');
};
};
}
return $uibModal.open(tempModalDefaults).result;
};}]);
And Delete in controller is looke like this:
$scope.deletePerson = function (personID) {
var modalOptions = {
closeButtonText: 'Cancel',
actionButtonText: 'Delete Customer',
headerText: 'Delete ' + 1 + '?',
bodyText: 'Are you sure you want to delete this customer?'
};
ModalService.showModal({}, modalOptions)
.then(function (result) {
var result = PersonService.deletePerson(personID);
result.then(function (res) {
$location.path("/");
}, function (error) {
$scope.error = error;
});
});
Now when I invoke the Delete function from the controller following error is raised :
angular.js:15018 Error: [$templateRequest:tpload] http://errors.angularjs.org/1.7.2/$templateRequest/tpload?p0=uib%2Ftemplate%2Fmodal%2Fwindow.html&p1=404&p2=Not%20Found
at angular.js:99
at angular.js:20721
at angular.js:17396
at m.$digest (angular.js:18557)
at m.$apply (angular.js:18945)
at k (angular.js:12799)
at V (angular.js:13056)
at XMLHttpRequest.A.onload (angular.js:12961)
I have also used "Appnam/app/modal.html" for templateUrl but it did not resolve.

I have resolved my issue, script <script src="~/Scripts/angular-ui/ui-bootstrap-tpls.min.js"></script> should be added.

Related

AngularJS - moving Material mdDialog to service

I'm trying to cleanup code of one of my controllers which became too big. First I have decided to move attendee registration, which uses AngularJS Material mdDialog, to the service.
Original (and working) controller code looks like:
myApp.controller('RegistrationController', ['$scope','$routeParams','$rootScope','$location','$filter','$mdDialog', function($scope, $routeParams, $rootScope, $location, $filter, $mdDialog){
var attendee = this;
attendees = [];
...
$scope.addAttendee = function(ev) {
$mdDialog.show({
controller: DialogController,
templateUrl: 'views/regForm.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true,
controllerAs: 'attendee',
fullscreen: $scope.customFullscreen, // Only for -xs, -sm breakpoints.
locals: {parent: $scope}
})
.then(function(response){
attendees.push(response);
console.log(attendees);
console.log(attendees.length);
})
};
function DialogController($scope, $mdDialog) {
var attendee = this;
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.save = function(response) {
$mdDialog.hide(response);
};
}
}]);
and the code for the controller after separation:
myApp.controller('RegistrationController', ['$scope','$routeParams','$rootScope','$location','$filter','$mdDialog','Attendees', function($scope, $routeParams, $rootScope, $location, $filter, $mdDialog, Attendees){
...
$scope.attendees= Attendees.list();
$scope.addAttendee = function (ev) {
Attendees.add(ev);
}
$scope.deleteAttendee = function (id) {
Attendees.delete(id);
}
}]);
New service code looks like:
myApp.service('Attendees', ['$mdDialog', function ($mdDialog) {
//to create unique attendee id
var uid = 1;
//attendees array to hold list of all attendees
var attendees = [{
id: 0,
firstName: "",
lastName: "",
email: "",
phone: ""
}];
//add method create a new attendee
this.add = function(ev) {
$mdDialog.show({
controller: DialogController,
templateUrl: 'views/regForm.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true,
controllerAs: 'attendee',
fullscreen: this.customFullscreen, // Only for -xs, -sm breakpoints.
//locals: {parent: $scope}
})
.then(function(response){
attendees.push(response);
console.log(attendees);
console.log(attendees.length);
})
};
//simply search attendees list for given id
//and returns the attendee object if found
this.get = function (id) {
for (i in attendees) {
if (attendees[i].id == id) {
return attendees[i];
}
}
}
//iterate through attendees list and delete
//attendee if found
this.delete = function (id) {
for (i in attendees) {
if (attendees[i].id == id) {
attendees.splice(i, 1);
}
}
}
//simply returns the attendees list
this.list = function () {
return attendees;
}
function DialogController($mdDialog) {
this.hide = function() {
$mdDialog.hide();
};
this.cancel = function() {
$mdDialog.cancel();
};
this.save = function(response) {
$mdDialog.hide(response);
};
}
}]);
but I'm not able to "save" from the spawned mdDialog box which uses ng-click=save(attendee) neither close the dialog box.
What I'm doing wrong?
I'm not able to "save" from the spawned mdDialog box which uses ng-click=save(attendee) neither close the dialog box.
When instantiating a controller with "controllerAs" syntax, use the name with which it is instantiated:
<button ng-click="ctrl.save(ctrl.attendee)">Save</button>
this.add = function(ev) {
$mdDialog.show({
controller: DialogController,
templateUrl: 'views/regForm.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true,
controllerAs: ̶'̶a̶t̶t̶e̶n̶d̶e̶e̶'̶ 'ctrl',
fullscreen: this.customFullscreen, // Only for -xs, -sm breakpoints.
//locals: {parent: $scope}
})
.then(function(response){
attendees.push(response);
console.log(attendees);
console.log(attendees.length);
return response;
});
To avoid confusion, choose a controller instance name that is different from the data names.
$scope is not available to be injected into a service when it's created. You need to refactor the service and its methods so that you don't inject $scope into it and instead pass the current scope to the service methods when you call them.
I actually have a notification module that I inject which uses $mdDialog. Below is the code for it. Perhaps it will help.
(() => {
"use strict";
class notification {
constructor($mdToast, $mdDialog, $state) {
/* #ngInject */
this.toast = $mdToast
this.dialog = $mdDialog
this.state = $state
/* properties */
this.transitioning = false
this.working = false
}
openHelp() {
this.showAlert({
"title": "Help",
"textContent": `Help is on the way for ${this.state.current.name}!`,
"ok": "OK"
})
}
showAlert(options) {
if (angular.isString(options)) {
var text = angular.copy(options)
options = {}
options.textContent = text
options.title = " "
}
if (!options.ok) {
options.ok = "OK"
}
if (!options.clickOutsideToClose) {
options.clickOutsideToClose = true
}
if (!options.ariaLabel) {
options.ariaLabel = 'Alert'
}
if (!options.title) {
options.title = "Alert"
}
return this.dialog.show(this.dialog.alert(options))
}
showConfirm(options) {
if (angular.isString(options)) {
var text = angular.copy(options)
options = {}
options.textContent = text
options.title = " "
}
if (!options.ok) {
options.ok = "OK"
}
if (!options.cancel) {
options.cancel = "Cancel"
}
if (!options.clickOutsideToClose) {
options.clickOutsideToClose = false
}
if (!options.ariaLabel) {
options.ariaLabel = 'Confirm'
}
if (!options.title) {
options.title = "Confirm"
}
return this.dialog.show(this.dialog.confirm(options))
}
showToast(toastMessage, position) {
if (!position) { position = 'top' }
return this.toast.show(this.toast.simple()
.content(toastMessage)
.position(position)
.action('OK'))
}
showYesNo(options) {
options.ok = "Yes"
options.cancel = "No"
return this.showConfirm(options)
}
uc() {
return this.showAlert({
htmlContent: "<img src='img\\underconstruction.jpg'>",
ok: "OK",
title: "Under Construction"
})
}
}
notification.$inject = ['$mdToast', '$mdDialog', '$state']
angular.module('NOTIFICATION', []).factory("notification", notification)
})()
Then inject notification (lower case) into my controllers in order to utilize it. I store notification in a property of the controller and then call it with something like this:
this.notification.showYesNo({
clickOutsideToClose: true,
title: 'Delete Customer Setup?',
htmlContent: `Are you sure you want to Permanently Delete the Customer Setup for ${custLabel}?`,
ariaLabel: 'Delete Dialog'
}).then(() => { ...
this.notification.working = true
this.ezo.EDI_CUSTOMER.remove(this.currentId).then(() => {
this.primaryTab = 0
this.removeCustomerFromList(this.currentId)
this.currentId = 0
this.notification.working = false
}, error => {
this.notification.working = false
this.notification.showAlert({
title: "Error",
htmlContent: error
})
})

Angular leaflet - Showing multiple marker issue

I am using the following code to add markers in leaflet:
.controller('MapController',
[ '$scope',
'$cordovaGeolocation',
'$stateParams',
'$ionicModal',
'$ionicPopup',
'$http',
function(
$scope,
$cordovaGeolocation,
$stateParams,
$ionicModal,
$ionicPopup,
$http
) {
$scope.$on("$stateChangeSuccess", function() {
$scope.map = {
defaults: {
tileLayer: 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
maxZoom: 18,
zoomControlPosition: 'bottomleft'
},
markers : {},
events: {
map: {
enable: ['context'],
logic: 'emit'
}
}
};
$scope.locate();
});
$scope.locate = function(){
$scope.map.center = {
lat : location.lat,
lng : location.lng,
zoom : 12,
};
var Location = function() {
if ( !(this instanceof Location) ) return new Location();
this.lat = "";
this.lng = "";
this.name = "";
};
$ionicModal.fromTemplateUrl('templates/addLocation.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal;
});
$scope.map.markers.push=({
lat:35.654,
lng:73.244,
message:'demo 1'
})
$scope.map.markers.push=({
lat:38.654,
lng:73.244,
message:'demo 2'
})
$scope.$on('leafletDirectiveMap.click', function(event, locationEvent){
$scope.newLocation = new Location();
$scope.newLocation.lat = locationEvent.leafletEvent.latlng.lat;
$scope.newLocation.lng = locationEvent.leafletEvent.latlng.lng;
$scope.modal.show();
});
$scope.saveLocation = function(lat, lang) {
//LocationsService.savedLocations.push($scope.newLocation);
//alert(lat + " - " + lang);
var link = 'http://192.168.5.110/server/addLocation.php';
var json1 = {l1 : lat, l2 : lang , l3: sessionStorage.getItem('loggedin_phone')};
$http.post(link, { data: json1 })
.then(function (res){
$scope.response = res.data.result;
if($scope.response.created=="1"){
$scope.title="Thank You";
$scope.template="Mobile Toilet Added!";
//no back option
/*
$ionicHistory.nextViewOptions({
disableAnimate: true,
disableBack: true
});
$state.go('login', {}, {location: "replace", reload: true});
*/
}else if($scope.response.exists=="1"){
$scope.title="Duplication";
$scope.template="This Location is already added!";
}else{
$scope.title="Failed";
$scope.template="Contact Our Technical Team";
}
var alertPopup = $ionicPopup.alert({
title: $scope.title,
template: $scope.template
});
});
$scope.modal.hide();
};
$cordovaGeolocation
.getCurrentPosition()
.then(function (position) {
$scope.map.center.lat = position.coords.latitude;
$scope.map.center.lng = position.coords.longitude;
$scope.map.center.zoom = 18;
$scope.map.markers.now = {
lat:position.coords.latitude,
lng:position.coords.longitude,
focus: true,
draggable: false,
//message: ''
};
}, function(err) {
// error
console.log("Location error!");
console.log(err);
});
};
}]);
But only the demo2 marker is displaying.
Is there a way to show multiple markers on the leaflet map by using JSON data of latitudes and longitudes loaded from API?
<leaflet defaults="defaults" event-broadcast="events" lf-center="center" markers="markers" layers="layers" id="global-map" width="100%" height="240px"></leaflet>
<leaflet defaults="defaults2" event-broadcast="events2" lf-center="center2" markers="markers2" layers="layers2" id="global-map2" width="100%" height="240px"></leaflet>

Angular Service or Root Function

I want to re-organize my code so that I can share a dialog page with different controllers (ie. each controller opens the same dialog)
Should my dialog be a service or a directive... I'm not sure how to make it available to the controllers and have access to scopes
Something like this:
app.controller('PropertiesCtrl', function($scope,$rootScope,$http, DTOptionsBuilder, DTColumnBuilder, apiserv, $filter, $mdDialog, $mdMedia){
$scope.getProperties = function(){
$scope.data=[];
//var url = 'http://www.filltext.com/?rows=10&fname={firstName}&lname={lastName}&delay=3&callback=JSON_CALLBACK';
var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name;
var url = apiserv+"api.properties.test.php"+data;
$http.jsonp(url).success(function(data){
$scope.data=data;
});
};
var vm = this;
function stateChange(iColumn, bVisible) {
console.log('The column', iColumn, ' has changed its status to', bVisible);
}
// TO-DO: Rather load from a Factory promise, like here: https://github.com/l-lin/angular-datatables/issues/14
// Example here: http://embed.plnkr.co/B9ltNzIRCwswgHqKD5Pp/preview
var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name;
var url = apiserv+"api.properties.test.php"+data;
vm.dtOptions = DTOptionsBuilder.fromSource(url)
.withBootstrap()
// Active Buttons extension
.withButtons([
//'columnsToggle',
'colvis',
'copy',
'print',
'excel'
])
.withOption('fnRowCallback',myCallback)
.withOption('order', [[ 3, "desc" ]])
.withOption('stateSave',true);
vm.dtColumns = [
DTColumnBuilder.newColumn('File_Num').withTitle('File'),
DTColumnBuilder.newColumn('Description').withTitle('Description'),
DTColumnBuilder.newColumn('street').withTitle('Street'),
DTColumnBuilder.newColumn('bedrooms').withTitle('Bed'),
DTColumnBuilder.newColumn('bathrooms').withTitle('Bath'),
DTColumnBuilder.newColumn('garages').withTitle('Garages'),
DTColumnBuilder.newColumn('car_port').withTitle('Car Ports').notVisible(),
DTColumnBuilder.newColumn('Current_Monthly_Rental').withTitle('Rental').renderWith(function(data, type, full) {
return $filter('currency')(data, 'R ', 2); //could use currency/date or any angular filter
})
];
})
.controller('PagesListCtrl', function($scope,$rootScope,$http, DTOptionsBuilder, DTColumnBuilder, apiserv, $filter, $mdDialog, $mdMedia){
$scope.page = {
title: 'Dashboard',
subtitle: 'Place subtitle here...'
};
});
function myCallback(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
$('td', nRow).bind('click', function() {
//$scope.$apply(function() {
showTabDialog(aData);
//});
});
return nRow;
};
function showTabDialog(ev) {
console.log(ev.file_id);
var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name+"&file="+ev.file_id;
var url = apiserv+"api.properties.view.php"+data;
console.log(url);
$http({url:url}).then(function(rs){
console.log(rs.data[0]);
$scope.propdata=rs.data[0];
$mdDialog.show({
controller: DialogController,
templateUrl: 'pages/properties/tabDialog.tmpl.html',
//parent: angular.element(document.body),
targetEvent: ev,
//onComplete: afterShowAnimation,
//scope:$scope,
//preserveScope: true
locals: { propdata: $scope.propdata }
})
.then(function(propdata) {
console.log(propdata);
//$scope.$parent.propdata = propdata; // Still old data
//vm.sname = propdata.street;
});
}, function(rs){
console.log("error : "+rs.data+" status : "+rs.status);
});
};
function DialogController($scope, $mdDialog, propdata) {
$scope.propdata = propdata;
$scope.form_size = "form-group-sm";
$scope.font_size = "font-size-sm";
$scope.hide = function(ret) {
//$scope.$apply(); Throws an error
$mdDialog.hide(ret);
}
$scope.changesize = function() {
var fsize = $scope.form_size.split("-").pop(); // "form-group-xs";
switch(fsize) {
case "sm" : fsize = "md";
break;
case "md" : fsize = "lg";
break;
case "lg" : fsize = "sm";
break;
}
$scope.form_size = "form-group-" + fsize;
$scope.font_size = "font-size-" + fsize;
}
}
This is how I had it and it worked, but as you can see the dialog is nested inside the controller and only usefull to that controller:
app
.controller('PropertiesCtrl', function($scope,$rootScope,$http, DTOptionsBuilder, DTColumnBuilder, apiserv, $filter, $mdDialog, $mdMedia){
$scope.page = {
title: 'Dashboard',
subtitle: 'Place subtitle here...'
};
$scope.getProperties = function(){
$scope.data=[];
//var url = 'http://www.filltext.com/?rows=10&fname={firstName}&lname={lastName}&delay=3&callback=JSON_CALLBACK';
var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name;
var url = apiserv+"api.properties.test.php"+data;
$http.jsonp(url).success(function(data){
$scope.data=data;
});
};
var vm = this;
function stateChange(iColumn, bVisible) {
console.log('The column', iColumn, ' has changed its status to', bVisible);
}
// TO-DO: Rather load from a Factory promise, like here: https://github.com/l-lin/angular-datatables/issues/14
// Example here: http://embed.plnkr.co/B9ltNzIRCwswgHqKD5Pp/preview
var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name;
var url = apiserv+"api.properties.test.php"+data;
vm.dtOptions = DTOptionsBuilder.fromSource(url)
.withBootstrap()
// Active Buttons extension
.withButtons([
//'columnsToggle',
'colvis',
'copy',
'print',
'excel'
])
.withOption('fnRowCallback',$scope.myCallback)
.withOption('order', [[ 3, "desc" ]])
.withOption('stateSave',true);
vm.dtColumns = [
DTColumnBuilder.newColumn('File_Num').withTitle('File'),
DTColumnBuilder.newColumn('Description').withTitle('Description'),
DTColumnBuilder.newColumn('street').withTitle('Street'),
DTColumnBuilder.newColumn('bedrooms').withTitle('Bed'),
DTColumnBuilder.newColumn('bathrooms').withTitle('Bath'),
DTColumnBuilder.newColumn('garages').withTitle('Garages'),
DTColumnBuilder.newColumn('car_port').withTitle('Car Ports').notVisible(),
DTColumnBuilder.newColumn('Current_Monthly_Rental').withTitle('Rental').renderWith(function(data, type, full) {
return $filter('currency')(data, 'R ', 2); //could use currency/date or any angular filter
})
/*DTColumnBuilder.newColumn('file_id').withTitle('').withClass('dt-right').renderWith(function(data, type, full) {
//return "<a href='#/app/statement/"+full.id+"' class='btn btn-default'>View</a>";
return "<a class=\"btn btn-default\" onclick='$(\"#myview\").click()'>View</a>";
}).notSortable()*/
];
$scope.showTabDialog = function(ev) {
console.log(ev.file_id);
var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name+"&file="+ev.file_id;
var url = apiserv+"api.properties.view.php"+data;
console.log(url);
$http({url:url}).then(function(rs){
console.log(rs.data[0]);
$scope.propdata=rs.data[0];
$mdDialog.show({
controller: DialogController,
templateUrl: 'pages/properties/tabDialog.tmpl.html',
//parent: angular.element(document.body),
targetEvent: ev,
//onComplete: afterShowAnimation,
//scope:$scope,
//preserveScope: true
locals: { propdata: $scope.propdata }
})
.then(function(propdata) {
console.log(propdata);
//$scope.$parent.propdata = propdata; // Still old data
//vm.sname = propdata.street;
});
}, function(rs){
console.log("error : "+rs.data+" status : "+rs.status);
});
};
function DialogController($scope, $mdDialog, propdata) {
$scope.propdata = propdata;
$scope.form_size = "form-group-sm";
$scope.font_size = "font-size-sm";
$scope.hide = function(ret) {
//$scope.$apply(); Throws an error
$mdDialog.hide(ret);
}
$scope.changesize = function() {
var fsize = $scope.form_size.split("-").pop(); // "form-group-xs";
switch(fsize) {
case "sm" : fsize = "md";
break;
case "md" : fsize = "lg";
break;
case "lg" : fsize = "sm";
break;
}
$scope.form_size = "form-group-" + fsize;
$scope.font_size = "font-size-" + fsize;
}
}
$scope.myCallback = function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
$('td', nRow).bind('click', function() {
$scope.$apply(function() {
$scope.showTabDialog(aData);
});
});
return nRow;
};
});
Here is factory to store and retrieve user from any controller:
app.factory('Auth', [, function () {
function getUser() {
return user;
}
var currentUser = getUser();
return {
currentUser: currentUser
}]);
And use it:
app.controller('controller', ['Auth', function(Auth) {
var currentUser = Auth.currentUser;
}]);
And don't forget to include new factory on page before controller.

Angular detect Idle user

I am trying to detect idle user (such as no mouse or touch events) and display a pop up warning. I have one service of detecting timeout and another to display the pop up. Time out service is being called from app.run. I have almost completed it, have the following two issues,
pop up is being displayed in same page, not as a modal.
pop up is being displayed multiple time.
Here is my code.
/*** App ****/
var myapp = angular.module("myapp", ['ui.bootstrap']);
myapp.run(function ($rootScope, timeoutService) {
timeoutService.setup();
});
/**** time out sevice ****/
myapp.factory('timeoutService', function ($window, modalService) {
var timeoutID;
var startTimer = function () {
// wait 2 seconds before calling goInactive
timeoutID = $window.setTimeout(goInactive, 2000);
}
var resetTimer =function(e) {
$window.clearTimeout(timeoutID);
goActive();
}
var goInactive = function () {
modalService.showModal({}, modalOptions).then(function (result) {
alert("Hello");
});
}
var goActive=function() {
startTimer();
}
var modalOptions = {
closeButtonText: 'Cancel',
actionButtonText: 'Delete Customer',
headerText: 'Delete ?',
bodyText: 'Are you sure you want to delete this customer?'
};
var timeOutService = {};
timeOutService.setup = function () {
$window.addEventListener("mousemove", resetTimer, false);
$window.addEventListener("mousedown", resetTimer, false);
$window.addEventListener("keypress", resetTimer, false);
$window.addEventListener("DOMMouseScroll", resetTimer, false);
$window.addEventListener("mousewheel", resetTimer, false);
$window.addEventListener("touchmove", resetTimer, false);
$window.addEventListener("MSPointerMove", resetTimer, false);
startTimer();
};
return timeOutService;
});
/****** Modal Service ******/
myapp.service('modalService', ['$modal', function ($modal) {
var modalDefaults = {
backdrop: true,
keyboard: true,
modalFade: true,
templateUrl:'../Modal.html'
};
var modalOptions = {
closeButtonText: 'Close',
actionButtonText: 'OK,',
headerText: 'Proceed?',
bodyText: 'Perform this action?'
};
this.showModal = function (customModalDefaults, customModalOptions) {
if (!customModalDefaults) customModalDefaults = {};
customModalDefaults.backdrop = 'static';
return this.show(customModalDefaults, customModalOptions);
};
this.show = function (customModalDefaults, customModalOptions) {
//Create temp objects to work with since we're in a singleton service
var tempModalDefaults = {};
var tempModalOptions = {};
//Map angular-ui modal custom defaults to modal defaults defined in service
angular.extend(tempModalDefaults, modalDefaults, customModalDefaults);
//Map modal.html $scope custom properties to defaults defined in service
angular.extend(tempModalOptions, modalOptions, customModalOptions);
if (!tempModalDefaults.controller) {
tempModalDefaults.controller = function ($scope, $modalInstance) {
$scope.modalOptions = tempModalOptions;
$scope.modalOptions.ok = function (result) {
$modalInstance.close(result);
};
$scope.modalOptions.close = function (result) {
$modalInstance.dismiss('cancel');
};
}
}
return $modal.open(tempModalDefaults).result;
};
}]);
You must create a global controller that functions defined beginning , this driver can be used on the homepage or send calls from any page of the document .
Reference should be made to assign the controller html < div ng - controller = " SesionCtrl "> < / div >
app.controller('SesionCtrl',function($scope,Idle,Keepalive,$log){
$Scope.$On('IdleStart',function(){
//Open Modal code
});
$ Scope . $ On ( ' IdleTimeout ', function () {
// The end of the timeout Logout
window.location = " logout.php " ;
});
} ) ;
<html lang="en"ng-app="myApp">
<body ng-app="myApp">
<div ng-controller="SesionCtrl"></div><!--Instance Controller-->
</body>
</html>

Create a simple Bootstrap Yes/No confirmation or just notification alert in AngularJS

It's so simple in a non-Angular environment. Just html and a two line of js code to show a modal confirmation dialog on the screen.
Now I am developting an AngularJS project in which I am using ui-bootstrap modal confirmation dialogs all over the place and I am sick of creating new controllers even for simple things like "Are you sure to delete this record?" kind of stuff.
How do you handle these simple situations? I am sure some people wrote some directives to simplify the needs.
I am asking you to share your experiences or the projects you know about that subject.
so create a reusable service for that... read here
code here:
angular.module('yourModuleName').service('modalService', ['$modal',
// NB: For Angular-bootstrap 0.14.0 or later, use $uibModal above instead of $modal
function ($modal) {
var modalDefaults = {
backdrop: true,
keyboard: true,
modalFade: true,
templateUrl: '/app/partials/modal.html'
};
var modalOptions = {
closeButtonText: 'Close',
actionButtonText: 'OK',
headerText: 'Proceed?',
bodyText: 'Perform this action?'
};
this.showModal = function (customModalDefaults, customModalOptions) {
if (!customModalDefaults) customModalDefaults = {};
customModalDefaults.backdrop = 'static';
return this.show(customModalDefaults, customModalOptions);
};
this.show = function (customModalDefaults, customModalOptions) {
//Create temp objects to work with since we're in a singleton service
var tempModalDefaults = {};
var tempModalOptions = {};
//Map angular-ui modal custom defaults to modal defaults defined in service
angular.extend(tempModalDefaults, modalDefaults, customModalDefaults);
//Map modal.html $scope custom properties to defaults defined in service
angular.extend(tempModalOptions, modalOptions, customModalOptions);
if (!tempModalDefaults.controller) {
tempModalDefaults.controller = function ($scope, $modalInstance) {
$scope.modalOptions = tempModalOptions;
$scope.modalOptions.ok = function (result) {
$modalInstance.close(result);
};
$scope.modalOptions.close = function (result) {
$modalInstance.dismiss('cancel');
};
};
}
return $modal.open(tempModalDefaults).result;
};
}]);
html for display
<div class="modal-header">
<h3>{{modalOptions.headerText}}</h3>
</div>
<div class="modal-body">
<p>{{modalOptions.bodyText}}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn"
data-ng-click="modalOptions.close()">{{modalOptions.closeButtonText}}</button>
<button class="btn btn-primary"
data-ng-click="modalOptions.ok();">{{modalOptions.actionButtonText}}</button>
</div>
once this is done... you just have to inject above service whereever you want to create a dialog box, example below
$scope.deleteCustomer = function () {
var custName = $scope.customer.firstName + ' ' + $scope.customer.lastName;
var modalOptions = {
closeButtonText: 'Cancel',
actionButtonText: 'Delete Customer',
headerText: 'Delete ' + custName + '?',
bodyText: 'Are you sure you want to delete this customer?'
};
modalService.showModal({}, modalOptions)
.then(function (result) {
//your-custom-logic
});
}
You can see my example. whatever i'v done.
<div ng-app="myApp" ng-controller="firstCtrl">
<button ng-click="delete(1);">Delete </button>
</div>
script
var app = angular.module("myApp", []);
app.controller('firstCtrl', ['$scope','$window', function($scope,$window) {
$scope.delete = function(id) {
deleteUser = $window.confirm('Are you sure you want to delete the Ad?');
if(deleteUser){
//Your action will goes here
alert('Yes i want to delete');
}
};
}])
You can use the Angular Confirm library.
When included, it's became available as a directive:
<button type="button" ng-click="delete()" confirm="Are you sure?">Delete</button>
As well as a service:
angular.module('MyApp')
.controller('MyController', function($scope, $confirm) {
$scope.delete = function() {
$confirm({text: 'Are you sure you want to delete?', title: 'Delete it', ok: 'Yes', cancel: 'No'})
.then(function() {
// send delete request...
});
};
});
For anything that has code that is triggered with a ng-click I just add a confirm attribute
eg
<a confirm="Are you sure?" ng-click="..."></a>
and confirm comes from (not mine, found on the web)
app.controller('ConfirmModalController', function($scope, $modalInstance, data) {
$scope.data = angular.copy(data);
$scope.ok = function() {
$modalInstance.close();
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
}).value('$confirmModalDefaults', {
template: '<div class="modal-header"><h3 class="modal-title">Confirm</h3></div><div class="modal-body">{{data.text}}</div><div class="modal-footer"><button class="btn btn-primary" ng-click="ok()">OK</button><button class="btn btn-warning" ng-click="cancel()">Cancel</button></div>',
controller: 'ConfirmModalController'
}).factory('$confirm', function($modal, $confirmModalDefaults) {
return function(data, settings) {
settings = angular.extend($confirmModalDefaults, (settings || {}));
data = data || {};
if ('templateUrl' in settings && 'template' in settings) {
delete settings.template;
}
settings.resolve = { data: function() { return data; } };
return $modal.open(settings).result;
};
})
.directive('confirm', function($confirm) {
return {
priority: 1,
restrict: 'A',
scope: {
confirmIf: "=",
ngClick: '&',
confirm: '#'
},
link: function(scope, element, attrs) {
function reBind(func) {
element.unbind("click").bind("click", function() {
func();
});
}
function bindConfirm() {
$confirm({ text: scope.confirm }).then(scope.ngClick);
}
if ('confirmIf' in attrs) {
scope.$watch('confirmIf', function(newVal) {
if (newVal) {
reBind(bindConfirm);
} else {
reBind(function() {
scope.$apply(scope.ngClick);
});
}
});
} else {
reBind(bindConfirm);
}
}
}
})
My google FOO has failed me and I cannot find the source site for this. I will update if I find it.
You can create a simple factory like this
angular.module('app')
.factory('modalService', [
'$modal', function ($modal) {
var self = this;
var modalInstance = null;
self.open = function (scope, path) {
modalInstance = $modal.open({
templateUrl: path,
scope: scope
});
};
self.close = function () {
modalInstance.dismiss('close');
};
return self;
}
]);
In your controller
angular.module('app').controller('yourController',
['$scope','modalService',function($scope,modalService){
$scope.openModal=function(){
modalService.open($scope,'modal template path goes here');
};
$scope.closeModal=function(){
modalService.close();
//do something on modal close
};
}]);
I have passed $scope in service function so that you can access closeModal function and in case you want to access some data from your controller .
In your html
<button ng-click="openModal()">Open Modal</button>

Resources