I've a question to my problem. I'm using on each page an info button who's opening when you click on it. For the modal window I'm using an own defined service who's giving the values to the controller of the modal window. For each page exists an different info message and I want to use only one View for all info messages. But only the message for the corresponding page should be displayed. How can I define this?
Here is a code of Home view Info btn:
<button type="button" class="btn pull-right" ng-click="msgBtn()">
click on info
</button>
The same code is in Person view.
How can I tell the modalCtrl that the msgBtn() was clicked on Person view and give me the message of person info?
Here is my solution example:
//First the HomeCtrl:
$scope.info = function (message) {
modalService.infoDia(message);
};
//HomeView:
<button type="button" class="btn" ng-click="info('Home')">
Click Info
</button>
//PersonCtrl:
$scope.info = function (message) {
modalService.infoDia(message);
};
//PersonView:
<button type="button" class="btn" ng-click="info('Person')">
Click Info
</button>
//infoDia Service:
...
return {
infoDia: function (message) {
return $modal.open({
templateUrl: 'info.html',
controller: function ($scope, params) {
$scope.message = params.message;
},
resolve: {
params: function () {
return {
message: message;
}
}
}
});
}
}
//ModalView:
...
<div class="modal-body">
<p ng-if="message == 'Home'">
This is the home information dialog.
</p>
<p ng-if="message == 'Person'">
This is the person information dialog.
</p>
</div>
...
You can have a property named something like infoMsg in both homeCtrl and personCtrl and access it in you modal view using {{infoMsg}}. But this will force you to add infoMsg property to each of your controllers scope whereever you are going to use the modal. Better you can have your home and person controllers pass the message string to the modal controller through the service. This will reduce coupling and will give your code more flexibility. This is all I can tell without seeing your code.
If you just want to show a message then this is pretty easily achieved. To put #ankur's answer in a form of code, it could be something like below.
Have a Info service, taking message as a parameter.
app.factory('Info', function($modal) {
return {
show: function(message) {
$modal.open({
templateUrl: 'info-modal-template.html',
controller: function($scope, params) {
$scope.message = params.message;
},
resolve: {
params: function() {
return {
message: message
};
}
}
});
}
};
});
Then inject and call it from within your HomeCtrl.
app.controller('HomeCtrl', function(Info) {
var vm = this;
vm.info = function(message) {
Info.show(message);
};
});
Where HTML template is simply.
<div ng-controller="HomeCtrl as vm">
<button type="button"
class="btn btn-default"
ng-click="vm.info('Home message')">
Home button
</button>
</div>
Answer to your new question posted as an answer.
// Home
app.controller('HomeCtrl', function($scope, modalService) {
$scope.info = function() {
modalService.infoDia('Home');
};
});
<button type="button" class="btn" ng-click="info()">Click Info</button>
// Person
app.controller('PersonCtrl', function($scope, modalService) {
$scope.info = function() {
modalService.infoDia('Person');
};
});
<button type="button" class="btn" ng-click="info()">Click Info</button>
// Service
app.factory('modalService', function($modal) {
return {
infoDia: function(message) {
return $modal.open({
templateUrl: 'info.html',
controller: function($scope, params) {
$scope.message = params.message;
},
resolve: {
params: function() {
return {
message: message
};
}
}
});
}
};
});
<div class="modal-body">
<p>{{ message }}</p>
</div>
Related
Using angularjs here:
I have looked at the following forum for my query but not able to resolve this :returning data from angularjs modal dialog service
I have the following modal html:
<div class="confirm-modal-header">
<h4 class="modal-title">{{modalOptions.headerText}}</h4>
</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 type="button" class="btn btn-danger"
data-ng-click="modalOptions.ok();">
{{modalOptions.actionButtonText}}
</button>
</div>
I also have the service for this:
CTApp.factory("dialogModalService", ["$q", "$timeout", "$state", "$modal",
function ($q, $timeout, $state, $modal) {
var service = {}
var modalDefaults = {
backdrop: true,
keyboard: true,
modalFade: true,
templateUrl: '/app/modal.html'
};
var modalOptions = {
closeButtonText: 'Close',
actionButtonText: 'OK',
headerText: 'Proceed?',
bodyText: 'Perform this action?'
};
service.showModal = function (customModalDefaults, customModalOptions) {
if (!customModalDefaults) customModalDefaults = {};
customModalDefaults.backdrop = 'static';
return this.show(customModalDefaults, customModalOptions);
};
service.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;
};
return service;
}
]);
And the above modal is being called from my controller as:
dialogModalService.showModal({}, modalOptions).then(function (result)
{
//check for result returned
}
Now in my controller I want to check whether the user pressed the cancel button or not. How can I check that?
I tried to pass the cancel along with
modalOptions.close('cancel')
But it never enters my controller loop of the dialogModalService.showModal.
In my browser also I tried to put a breakpoint inside the call above but again its never hit.
What am I doing wrong here?
In your Modal service try changing:
$modalInstance.dismiss('cancel');
to
$modalInstance.close('cancel');
I will enter username and password in text field but I will not save. Without saving that data i will close the popup modal.
When I click outside of the modal, it will close.
If I open the popup again, the previous datas are still appearing. I need to clear those datas and want to make the field as empty.
Please check the following link. Plunkr
angular.module('plunker', ['ui.bootstrap']);
var ModalDemoCtrl = function ($scope, $modal, $log) {
$scope.user = {
user: 'name',
password: null,
notes: null
};
$scope.open = function () {
$modal.open({
templateUrl: 'myModalContent.html', // loads the template
backdrop: true, // setting backdrop allows us to close the modal window on clicking outside the modal window
windowClass: 'modal', // windowClass - additional CSS class(es) to be added to a modal window template
controller: function ($scope, $modalInstance, $log, user) {
$scope.user = user;
$scope.submit = function () {
$log.log('Submiting user info.'); // kinda console logs this statement
$log.log(user);
$modalInstance.dismiss('cancel'); // dismiss(reason) - a method that can be used to dismiss a modal, passing a reason
}
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
},
resolve: {
user: function () {
return $scope.user;
}
}
});//end of modal.open
}; // end of scope.open function
};
<!doctype html>
<html ng-app="plunker">
<head>
<script src="https://code.angularjs.org/1.2.18/angular.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js"></script>
<script src="example.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3>I'm a modal!</h3>
</div>
<form ng-submit="submit()">
<div class="modal-body">
<label>User name</label>
<input type="text" ng-model="user.user" />
<label>Password</label>
<input type="password" ng-model="user.password" />
<label>Add some notes</label>
<textarea rows="4" cols="50" ng-model="user.notes">
</textarea>
</div>
<div class="modal-footer">
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
<input type="submit" class="btn primary-btn" value="Submit" />
</div>
</form>
</script>
<button class="btn" ng-click="open()">Open me!</button>
<div ng-show="selected">Selection from a modal: {{ selected }}</div>
</div>
</body>
</html>
The problem is, you are actually binding the $scope.user in modal to the $scope.user from the ModalDemoCtrl. To solve this, you should make a copy of your user before using it in the modal controller:
$modal.open({
...
controller: function ($scope, $modalInstance, $log, user) {
$scope.user = angular.copy(user);
...
}
});
See Angular.copy() documentation.
see Clear the form after submit angularjs for how to clear the form. you can trigger this in your submit function before the modal closes.
You can do that with ui bootstrap promise:
$scope.modal.result.then(function(result) {
console.log('client: resolved: ' + result);
}, function(reason) {
console.log('client: rejected: ' + reason);
});
I had run your code and it worked fine.
angular.module('plunker', ['ui.bootstrap']);
var ModalDemoCtrl = function ($scope, $modal, $log) {
$scope.user = {
user: 'name',
password: null,
notes: null
};
$scope.open = function () {
var $theModal = $modal.open({
templateUrl: 'myModalContent.html', // loads the template
backdrop: true, // setting backdrop allows us to close the modal window on clicking outside the modal window
windowClass: 'modal', // windowClass - additional CSS class(es) to be added to a modal window template
controller: function ($scope, $modalInstance, $log, user) {
$scope.user = user;
$scope.submit = function () {
$log.log('Submiting user info.'); // kinda console logs this statement
$log.log(user);
$modalInstance.dismiss('cancel'); // dismiss(reason) - a method that can be used to dismiss a modal, passing a reason
}
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
},
resolve: {
user: function () {
return $scope.user;
}
}
});//end of modal.open
$theModal.result.then(function(result) {
console.log('client: resolved: ' + result);
}, function(reason) {
$scope.user = {}
console.log('client: reject: ' + reason);
})
}; // end of scope.open function
};
I've done some research on this question both in SO and on Google as well. But none of the answers serve my purpose.
I have a modal in an HTML view, which I use to show popup notifications in my app.
I want to show some buttons ('OK', 'Cancel', 'Login', etc.,) in a div on modal which I pass dynamically as a JS object. Name of the button being the key and the callback function being the value.
Examples:
{
"Login": function(){....}
}
{
"OK": function(){...},
"Cancel": function(){...}
}
Now I pass this kind of objects to a method showPopup(message, buttonMap) in the controller of the popup modal I have in view.
message being the display message on the popup and buttonMap being the object in examples.
Controller:
angular.module('core').controller('PopupController', ['$rootScope', 'LogService', 'MessageHandlerService',
function ($rootScope, LogService, MessageHandlerService) {
var ctrl = this;
ctrl.buttonMap = {};
ctrl.btnWidth = 100;
$rootScope.$on('popup', showPopup);
function showPopup (event, message, buttonMap) {
$('#genericModalDialog .popup-content p').html(message);
ctrl.buttonMap = buttonMap;
var numberOfButtons = Object.keys(buttonMap).length;
ctrl.btnWidth = (100 - numberOfButtons*2)/numberOfButtons;
$("#genericModalDialog").modal('show');
}
ctrl.callbackFor = function callbackFor(key) {
ctrl.buttonMap[key].call(null);
};
}
]);
Service:
angular.module('core').service('PopupService', ['$rootScope', 'LogService', 'CacheService', 'MessageHandlerService',
function ($rootScope, LogService) {
this.isPopupShown = function (){
return $("#genericModalDialog").hasClass('in');
}
this.showPopup = function (message, btnMap){
$rootScope.$broadcast('popup', message, btnMap);
}
this.closePopup = function (){
$("#genericModalDialog").modal('hide');
}
}
]);
View:
<div ng-controller="PopupController as popupCtrl" class="modal fade" id="genericModalDialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="vertical-alignment-helper">
<div class="modal-dialog vertical-align-center" style="width:94%;">
<div class="modal-content">
<div class="modal-body">
<br/><br/>
<div class="popup-content">
<p align="center"></p><br/>
<div class="popup-action">
<button type="button" class="btn" style="width:{{popupCtrl.btnWidth}}%; margin:1%" ng-repeat="(buttonName, callBack) in popupCtrl.buttonMap" ng-click="popupCtrl.callbackFor(buttonName)">{{buttonName}}</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Since I don't want to instantiate PopupController in every other controller/service, I've written a service called PopupService which has a method that can called and will $broadcast an event called "popup" on $rootscope and I am handling this event in PopupController. Everything is triggered and working properly in this case. The only problem I face is the delay in rendering the popup on the UI, I see the message as soon as the popup is displayed but the rendering of buttons is very slow (approx 3 secs) this is because of loading of some other web page in the background.
When I searched about the issue on the internet I also found this total setup can be changed to a directive and the rendering of dynamic content (in this case the popup and buttons on it.) could be placed in a link function of the directive.
Another approach I saw was directly handling the DOM manipulation in the service which of course is not a good way.
Did I miss any other approach or a solution to this issue?
All I want to know is what would the best way be, to handling this situation which is programmatically and design wise good.
If I am not clear please let me know. I'll try explaining the problem again.
Directive would be a much better choice that the DOM manipulation. Additionally you should consider changing the usage of jQuery dialog into a https://angular-ui.github.io/bootstrap/#/modal.
Here is an example how it can be done:
1) Create the directive
app.directive('myModal', function() {
return {
restrict: 'E',
scope: {
items: "=",
message: "="
},
replace: true,
templateUrl: "directiveTemplate.html",
controller: function($scope, $uibModal, $log) {
$scope.open = function(size) {
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size,
resolve: {
items: function() {
return $scope.items;
},
message: function() {
return $scope.message;
}
}
});
modalInstance.result.then(function(selectedItem) {
$scope.button = selectedItem.name;
$scope[selectedItem.callback](selectedItem.name);
});
};
}
}
});
2) Create modalInstance directive
app.controller('ModalInstanceCtrl', function($scope, $uibModalInstance, items, message) {
$scope.items = items;
$scope.message = message;
$scope.close = function(item) {
$uibModalInstance.close(item);
};
});
3) create directive template directiveTemplate.html
<div>
{{buttonClicked}}
<br> {{button}}
<button type="button" class="btn btn-default" ng-click="open('sm')">{{message}}</button>
</div>
4) create popup template 'myModalContent.html'
{{message}}
<button ng-repeat="item in items" type="button" class="btn btn-default" ng-click="close(item)">{{item.name}}</button>
5) define you controller where you will have list of buttons and message to be displayed in the popup (for demo purpose here are two different list of items and two messages)
app.controller('ModalDemoCtrl', function($scope) {
$scope.message = "modal 1";
$scope.items = [{
name: 'item1',
callback: "test1"
}, {
name: 'item2',
callback: "test2"
}, {
name: 'item3',
callback: "test3"
}];
$scope.message2 = "modal 12222";
$scope.items2 = [{
name: 'item1222',
callback: "test1"
}, {
name: 'item2222',
callback: "test2"
}, {
name: 'item3222',
callback: "test3"
}];
$scope.test1 = function(message) {
$scope.buttonClicked = "clicked test1";
}
$scope.test2 = function(message) {
$scope.buttonClicked = "clicked test2";
}
$scope.test3 = function(message) {
$scope.buttonClicked = "clicked test3";
}
});
and in order to you the directive you need:
<div ng-controller="ModalDemoCtrl">
<my-modal items="items" message="message"></my-modal>
</br>
<my-modal items="items2" message="message2"></my-modal>
</div>
If you have directive accessed from different angular application instances, than just inject directive application into the needed one (make sure the directive and modal instance to have a their own defined module ex: var app = angular.module('myPopupDynamicModule', ['ngAnimate', 'ui.bootstrap']); and this is the one to be used for injection into other modules following this example: var app2 = angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap', 'myPopupDynamicModule']);)
I have a model controller like such:
pcApp.controller("ModalInstanceController", function ($scope, $modalInstance, model) {
$scope.claim = model;
$scope.payNow = function () {
$modalInstance.close("now");
};
$scope.refuse = function () {
$modalInstance.close("later");
};
$scope.payLater = function () {
$modalInstance.dismiss("cancel");
};
});
The modal template is:
<script type="text/ng-template" id="newClaimPopup.html">
<div class="modal-header">
<h3 class="desktop">PayCaddy Claim</h3>
</div>
<div class="modal-body">
<p>{{claim.SenderFullName}} is claiming an amount of R{{claim.Amount}} for a golfing bet with him that you lost, with the message:</p>
<br />
<p>{{claim.Description}}</p>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="payNow()">Yes</button>
<button class="btn btn-danger" type="button" ng-click="refuse()">Refuse</button>
<button class="btn btn-warning" type="button" ng-click="payLater()">Later</button>
</div>
</script>
This is in a partial view included in _Layout.cshtml:
<div id="claim-notice-template">
#Html.Partial("_NewClaimPopupTemplate")
</div>
I show the modal using this code:
$scope.showNewClaimPopup = function (viewModel) {
$scope.claim = viewModel;
var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: "newClaimPopup.html",
controller: "ModalInstanceController",
size: "sm",
resolve: {
model: function () {
return $scope.claim;
}
}
});
modalInstance.result.then(function () {
debugger;
$log.info("Modal accepted at: " + new Date());
}, function () {
$log.info("Modal dismissed at: " + new Date());
});
};
The viewModel parameter passed in to $scope.showNewClaimPopup is valid and fully populated. The resolve option for open is also working, because in ModalInstanceController I can see that the model parameter is the same valid viewmodel. Yet when the modal displays, the binding templates are all blank.
All code shown is in one MainController assigned to a div that surrounds everything, including the partial containing the modal template.
Why is the template not binding as expected?
You need to pass $scope to be used to compile modal template:
var modalInstance = $modal.open({
scope: $scope, // <--- this line is necessary
animation: $scope.animationsEnabled,
templateUrl: "newClaimPopup.html",
controller: "ModalInstanceController",
size: "sm",
resolve: {
model: function () {
return $scope.claim;
}
}
});
If you don't provide scope config then modal will create new child scope of the $rootScope, which obviously doesn't contain claim object.
I have a page which opens a modal that asks for user confirmation when making an edit to something on the page. If the user chooses "Cancel" button in the modal, the modal closes fine, but then refuses to re-open with the same link. The following error gets thrown if the modal link is clicked again:
TypeError: fn is not a function
at $parseFunctionCall (https://localhost:44310/js/angular.js:12346:15)
at ngEventDirectives.(anonymous function).compile.element.on.callback (https://localhost:44310/js/angular.js:21438:17)
at Scope.$get.Scope.$eval (https://localhost:44310/js/angular.js:14401:28)
at Scope.$get.Scope.$apply (https://localhost:44310/js/angular.js:14500:23)
at HTMLAnchorElement.<anonymous> (https://localhost:44310/js/angular.js:21443:23)
at HTMLAnchorElement.n.event.dispatch (https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.min.js:3:6466)
at HTMLAnchorElement.n.event.add.r.handle (https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.min.js:3:3241)
Here is the controller for the modal, very simple:
(function (angular, undefined) {
"use strict";
angular
.module("app.edit")
.controller("App.EditController", [
"$modalInstance", "$scope", "editList",
function ($modalInstance, $scope, editList) {
$scope.thingsToEdit = editList;
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss("cancel");
};
}
]);
})(angular);
The editList is used to display a list in the confirmation modal, the html of the page.
And the HTML for the modal is:
<div class="modal-header">
<h3>Edit</h3>
</div>
<div class="modal-body">
<p>Please confirm the following edits: </p>
<ul>
<li ng-repeat="thing in thingsToEdit">{{thing}}</li>
</ul>
</div>
<div class="modal-footer">
<div class="form">
<div class="form-group">
<button class="btn btn-primary" type="submit" ng-click="ok()">Confirm Edit</button>
<button class="btn btn-danger" ng-click="cancel()">Cancel</button>
</div>
</div>
</div>
And in the JavaScript for the original page that opens the modal is:
$scope.edit = function (things) {
$scope.editList = things;
$scope.thingsToEdit = things;
var editModal = $modal.open({
animation: true,
templateUrl: "edit.html",
controller: "App.EditController",
resolve: {
editList: function () {
return $scope.thingsToEdit;
}
}
});
editModal.result.then(function () {
var editUrl = //a valid url
$http.post(editUrl, { cache: true })
.success(function () {
console.log("edit successful");
})
.error(function () {
console.log("edit failed");
})
}, function() {
console.log("edit canceled");
});
};