Angular Modal not binding to scope properties - javascript

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.

Related

Angularjs Modal: Returning state from service

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');

how to reset all HTML input fields after closing angular modal

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
};

Angular modal service not displaying

I am trying to set up angular modal service on my web app, but whenever I click on my button it does not appear. What am I doing wrong?
Builder View
<div ng-controller="BuilderController as vm">
<button type="button" class="btn btn-success" ng-click="vm.showExportModal()">Export</button>
</div>
Builder Controller
angular.module('myWebApp')
.controller('BuilderController', function ($scope, BuilderService) {
var vm = this;
vm.showExportModal = function() {
BuilderService.showExportModal();
};
});
Builder Service
angular.module('myWebApp')
.service('BuilderService', function (ModalService) {
var builderService = {
showExportModal: showExportModal
};
return builderService;
function showExportModal() {
ModalService.showModal({
template: "<div>Fry lives in {{futurama.city}}</div>",
controller: function() {
this.city = "New New York";
},
controllerAs : "futurama"
})
};
});
It seems to work fine in this snippet, I suggest checking you have injected it as a dependency in your app.
Please also note you need the correct modal template to display a modal instead of the template you have provided to the directive.
angular.module('myWebApp', ['angularModalService']);
angular.module('myWebApp')
.controller('BuilderController', function($scope, BuilderService) {
var vm = this;
vm.showExportModal = function() {
BuilderService.showExportModal();
};
});
angular.module('myWebApp')
.service('BuilderService', function(ModalService) {
var builderService = {
showExportModal: showExportModal
};
return builderService;
function showExportModal() {
ModalService.showModal({
template: "<div>Fry lives in {{futurama.city}}</div>",
controller: function() {
this.city = "New New York";
},
controllerAs: "futurama"
})
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="http://dwmkerr.github.io/angular-modal-service/angular-
modal-service.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<div ng-app="myWebApp">
<div ng-controller="BuilderController as vm">
<button type="button" class="btn btn-success" ng-click="vm.showExportModal()">Export</button>
</div>
</div>

How to use angular component with ui.bootstrap.modal in angular 1.5?

I'd like to use angular component with ui.bootstrap.modal. angular version is 1.5.
I tried to use like below.
component
function MyComponentController($uibModalInstance){
var ctrl = this;
ctrl.doSomething = function() {
//doSomething
}
}
app.component('myComponent', {
contoller: MyComponentController,
templateUrl: '/path/to/myComponent.html'
}
parent controller
function parentController($uibModal){
var ctrl = this;
ctrl.openModal = function(){
var modalInstance = $uibModal.open({
template: '<my-component></my-component>'
}
}
And when I execute parentController.openModal() , I got the error of $injector:unpr Unknown Provider although modal window is open.
Is there a way to use angular component with ui.bootstrap.modal?
If you need more information, please let me know that.
Thank you.
EDIT
I've got a way to use component with ui.bootstrap.modal from Renato Machado, Thanks Renato.
But I feel It's a little bit complicated and not convenient. So finally I think that it's better to use component inside the modal.
Modal is opened with regular way(just set controller and template in $uibModal.open({}) ) and the modal contains the component which has logics you want to use commonly.
Modal should have only simple logics that are related with modal like close modal window.
Another logics mainly related with business/Application should be in component.
It makes easy to commonalize.
EDIT: As of UI Bootstrap 2.1.0 there is native support for component in bootstrap modals. It looks like there have been several quick releases after 2.1.0 to fix some issues with the modals, so I'd be sure to grab the latest.
See this Plunk for a version using UI Bootstrap 2.1.0+
http://plnkr.co/edit/jy8WHfJLnMMldMQRj1tf?p=preview
angular.module('app', ['ngAnimate', 'ui.bootstrap']);
angular.module('app')
.component('myContent', {
template: 'I am content! <button type="button" class="btn btn-default" ng-click="$ctrl.open()">Open Modal</button>',
controller: function($uibModal) {
$ctrl = this;
$ctrl.dataForModal = {
name: 'NameToEdit',
value: 'ValueToEdit'
}
$ctrl.open = function() {
$uibModal.open({
component: "myModal",
resolve: {
modalData: function() {
return $ctrl.dataForModal;
}
}
}).result.then(function(result) {
console.info("I was closed, so do what I need to do myContent's controller now. Result was->");
console.info(result);
}, function(reason) {
console.info("I was dimissed, so do what I need to do myContent's controller now. Reason was->" + reason);
});
};
}
});
angular.module('app')
.component('myModal', {
template: `<div class="modal-body"><div>{{$ctrl.greeting}}</div>
<label>Name To Edit</label> <input ng-model="$ctrl.modalData.name"><br>
<label>Value To Edit</label> <input ng-model="$ctrl.modalData.value"><br>
<button class="btn btn-warning" type="button" ng-click="$ctrl.handleClose()">Close Modal</button>
<button class="btn btn-warning" type="button" ng-click="$ctrl.handleDismiss()">Dimiss Modal</button>
</div>`,
bindings: {
modalInstance: "<",
resolve: "<"
},
controller: [function() {
var $ctrl = this;
$ctrl.$onInit = function() {
$ctrl.modalData = $ctrl.resolve.modalData;
}
$ctrl.handleClose = function() {
console.info("in handle close");
$ctrl.modalInstance.close($ctrl.modalData);
};
$ctrl.handleDismiss = function() {
console.info("in handle dismiss");
$ctrl.modalInstance.dismiss("cancel");
};
}]
});
Original answer is below:
I was trying to figure this out the other day too. I took the information I found in this post along with this link to try and come up with an alternate way to accomplish this. These are some reference links I found that helped me:
https://github.com/angular-ui/bootstrap/issues/5683
http://www.codelord.net/ (this one helped in understanding passing arguments to callbacks in components)
Also here is a Plunk: http://plnkr.co/edit/PjQdBUq0akXP2fn5sYZs?p=preview
I tried to demonstrate a common real world scenario of using a modal to edit some data.
angular.module('app', ['ngAnimate', 'ui.bootstrap']);
angular.module('app')
.component('myContent', {
template: 'I am content! <button type="button" class="btn btn-default" ng-click="$ctrl.open()">Open Modal</button>',
controller: function($uibModal) {
$ctrl = this;
$ctrl.dataForModal = {
name: 'NameToEdit',
value: 'ValueToEdit'
}
$ctrl.open = function() {
$uibModal.open({
template: '<my-modal greeting="$ctrl.greeting" modal-data="$ctrl.modalData" $close="$close(result)" $dismiss="$dismiss(reason)"></my-modal>',
controller: ['modalData', function(modalData) {
var $ctrl = this;
$ctrl.greeting = 'I am a modal!'
$ctrl.modalData = modalData;
}],
controllerAs: '$ctrl',
resolve: {
modalData: $ctrl.dataForModal
}
}).result.then(function(result) {
console.info("I was closed, so do what I need to do myContent's controller now and result was->");
console.info(result);
}, function(reason) {
console.info("I was dimissed, so do what I need to do myContent's controller now and reason was->" + reason);
});
};
}
});
angular.module('app')
.component('myModal', {
template: `<div class="modal-body"><div>{{$ctrl.greeting}}</div>
<label>Name To Edit</label> <input ng-model="$ctrl.modalData.name"><br>
<label>Value To Edit</label> <input ng-model="$ctrl.modalData.value"><br>
<button class="btn btn-warning" type="button" ng-click="$ctrl.handleClose()">Close Modal</button>
<button class="btn btn-warning" type="button" ng-click="$ctrl.handleDismiss()">Dimiss Modal</button>
</div>`,
bindings: {
$close: '&',
$dismiss: '&',
greeting: '<',
modalData: '<'
},
controller: [function() {
var $ctrl = this;
$ctrl.handleClose = function() {
console.info("in handle close");
$ctrl.$close({
result: $ctrl.modalData
});
};
$ctrl.handleDismiss = function() {
console.info("in handle dismiss");
$ctrl.$dismiss({
reason: 'cancel'
});
};
}],
});
There is no need to make it more complicated by passing along the parent controller, you can just access it from within the .component that displays the modal.
Component
/**
* #ngdoc component
* #name fsad.component:video
*
* #description <fsad-video> component, in development...
*
*/
(function () {
'use strict';
angular.module('fsad').component('fsadVideo', {
bindings: {},
templateUrl: function(appConstant){return appConstant.paths.modules.fsad + 'leefloon/fsad-video.html'},
controller: controller
});
controller.$inject = ['$scope'];
function controller($scope){
var $ctrl = this;
setDataModel();
/****************************************************************/
$ctrl.ui.close = close;
/****************************************************************/
function setDataModel(){
$ctrl.ui = {};
}
function close(){
$scope.$parent.$close();
}
}
}());
Opening the modal
var modalInstance = $uibModal.open({
backdrop: 'static',
keyboard: true,
backdropClick: false,
template: '<fsad-video></fsad-video>',
windowClass: 'edit-contactenblad',
});
Since you are stating that the template is a component, the $scope.$parent will always be pointing to the modal instance. Allowing you to access the $close() function.
Passing and receiving data
If you need to pass data to the component, or receive data back from the component, you can do it like this.
var modalInstance = $uibModal.open({
backdrop: 'static',
keyboard: true,
backdropClick: false,
template: '<fsad-video method="$ctrl.method" on-viewed="$ctrl.userHasViewedVideo(time)"></fsad-ideo>',
controller: function(){
this.method = method;
this.userHasViewedVideo = function(time){}
},
controllerAs: '$ctrl',
windowClass: 'edit-medewerker',
});
Just on a side note, i'm using this structure style guide to create the component.
If you want access to the $uibModal's $close() and $dismiss() functions, along with some parent data and function binding within your component, you can pass them all along as such:
Open Modal Logic
$uibModal.open({
template: '<login close="$close()" dismiss="$dismiss()" ' +
'email="$ctrl.cookieEmail" check-login="$ctrl.ajaxLogin(user, pass)"></login>',
controller: function () {
this.cookieEmail = $cookies.get('savedEmail');
this.ajaxLogin = AjaxLoginService.login;
},
controllerAs: '$ctrl'
});
Modal Login Component
{
templateUrl: 'view/login.html',
bindings: {
email: '<',
checkLogin: '&',
close: '&',
dismiss: '&'
},
controller: function () {
var viewModel = this;
viewModel.password = '';
viewModel.submit = function () {
viewModel.checkLogin(
{ user: viewModel.email, pass: viewModel.password }
).then(function (success) {
viewModel.close();
});
}
}
}
Modal HTML
<form ng-submit="$ctrl.submit()">
<input type="text" ng-model="$ctrl.email" />
<input type="password" ng-model="$ctrl.password" />
<button type="button" ng-click="$ctrl.dismiss()">Cancel</button>
<button type="submit">Login</button>
</form>
The AngularJS 1.5 docs are a little sparse, but they show the usage of the & binding as a function wrapper: https://docs.angularjs.org/guide/component
You need to pass the parent controller to the modal component with the modal instance on it. To do that you need to append the generate HTML of the modal in the parent component
parent component
$ctrl.openModal = function(){
$ctrl.modalInstance = $uibModal.open({
template: '<your-modal></your-modal>',
appendTo : $document.find('parentComponent')
});
}
modal component
.component('yourModal', {
templateUrl: 'path/to/modal.html',
replace: true,
require: {
parent : '^parentComponent'
},
controller: ModalCtrl
});
function ModalCtrl() {
var $ctrl = this;
$ctrl.$onInit = function(){
var instance = $ctrl.parent.modalInstance;
$ctrl.items = ['item1', 'item2', 'item3'];
$ctrl.selected = {
item: $ctrl.items[0]
};
$ctrl.ok = function () {
instance.close($ctrl.selected);
};
$ctrl.cancel = function () {
instance.dismiss('cancel');
};
instance.result.then(function (selectedItem) {
$ctrl.selected = selectedItem;
}, function () {
console.log('Modal dismissed at: ' + new Date());
});
};
}
Be carefull because the required controller will only be available after the $onInit.

Using different info messages in one Ctrl with $modal service (AngularJS)

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>

Categories

Resources