Bind values to UI Bootstrap Modal - angularjs

I have a table with a view button, when view is clicked modal display but now I want to display certain data on the modal. I am using .html pages.
I am not sure what am I missing here
html
<td>
<span>
<input class="btn btn-sm btn-dark" data-ng-click="launch('create',client)" type="button" value="view" />
</span>
</td>
This will luanch the modal
Modal
<div class="modal fade in" ng-controller="dialogServiceTest">
<div class="modal ng-scope">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">
<span class="glyphicon glyphicon-star"></span> Client Details
</h4>
</div><div class="modal-body">
<ng-form name="nameDialog" novalidate="" role="form" class="ng-pristine ng-invalid ng-invalid-required">
<div class="form-group input-group-lg" ng-class="{true: 'has-error'}[nameDialog.username.$dirty && nameDialog.username.$invalid]">
<label class="control-label" for="username">Name:</label>
<input type="text" name="username" id="username" ng-model="client.ClientName" ng-keyup="hitEnter($event)" required="">
<span class="help-block">Enter your full name, first & last.</span>
</div>
<div>{{client.ClientName}}</div>
</ng-form>
</div><div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="cancel()">Cancel</button>
<button type="button" class="btn btn-primary" ng-click="save()" ng-disabled="(nameDialog.$dirty && nameDialog.$invalid) || nameDialog.$pristine" disabled="disabled">Save</button>
</div>
</div>
</div>
</div>
Angular
angular.module('modalTest', ['ngRoute','ui.bootstrap', 'dialogs'])
.controller('dialogServiceTest', function ($scope,$http, $rootScope, $timeout, $dialogs) {
$scope.clients = []; //Array of client objetcs
$scope.client = {}; //Single client object
$scope.launch = function (which,client) {
var dlg = null;
alert(client.ClientName);
dlg = $dialogs.create('/templates/Modal.html', 'whatsYourNameCtrl', {}, { key: false, back: 'static' });
dlg.result.then(function () {
$scope.client.ClientName = client.ClientName;
});
})
.run(['$templateCache', function ($templateCache) {
$templateCache.put('/templates/Modal.html');
}]);

here is some of my code
$scope.showScreenSizePicker = function(){
$scope.actionmsg = "";
var modalWindow = $modal.open({
templateUrl: '{{url()}}/modals/modalScreenSizePicker',
controller: 'modalScreenSizePickerController',
resolve: {
titletext: function() {return "Screen Sizes: ";},
oktext: function() {return "Close";},
canceltext: function() {return "Cancel";},
labeltext: function() {return "";},
}});
modalWindow.result.then(function(returnParams) {
$scope.setViewSize(returnParams[0], returnParams[1]);
});
}
you can see i am passing variables into modal using resolve. If you want to pass values back from the modal you can grab the variable returnParms (array)
and here is my controller code:
angular.module('myWebApp').controller('modalScreenSizePickerController', function($scope, $modalInstance, titletext, labeltext, oktext, canceltext) {
$scope.titletext = titletext;
$scope.labeltext = labeltext;
$scope.oktext = oktext;
$scope.canceltext = canceltext;
$scope.customHeight = 800;
$scope.customWidth = 600;
$scope.selectCustomSize = function(width, height){
if (width < 100){ width = 100; }
if (height < 100){ height = 100; }
$scope.selectItem(width, height);
}
$scope.selectItem = function(width, height) {
var returnParams = [width, height];
$modalInstance.close(returnParams);
};
$scope.cancel = function() {
$modalInstance.dismiss();
};
});
hope my sample helps

I think what you are looking for is the resolve property you can use with the $modal service. I am not exactly sure which version of UI Bootstrap you are using, but the latest one works as follows:
var myModal = $modal.open({
templateUrl: '/some/view.html',
controller: 'SomeModalCtrl',
resolve: {
myInjectedObject: function() { return someObject; }
});
myModal.result.then(function(){
// closed
}, function(){
// dismissed
});
Then you can use the injected resolved value inside the modals controller:
app.controller('SomeModalCtrl', function ($scope, $modalInstance, myInjectedObject) {
// use myInjectedObject however you like, eg:
$scope.data = myInjectedObject;
});

You can acces the client in modal by using "$scope.$parent.client" - "$parent" give you $scope from witch the modal was open with all data.

Related

Save Form data from Popover in Angularjs

var App = angular.module('myApp', []);
App.controller('myPopoverCtrl',
function($scope){
$scope.myPopover = {
isOpen: false,
open: function open() {
$scope.myPopover.isOpen = true;
},
close: function close() {
// alert('hi');
$scope.myPopover.isOpen = false;
}
};
$scope.SaveNotes = function() {
console.log('hi');
console.log($scope.noteText);
//getting undefined here
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app = "App">
<a uib-popover-template="'AddNote.html'"
popover-title="AddNote"
popover-trigger="'outsideClick'"
ng-controller="myPopoverCtrl"
popover-is-open="myPopover.isOpen"
ng-click="myPopover.open()">Add
</a>
</div>
<script type="text/ng-template" id="AddNote.html">
<div>
<textarea class="form-control height-auto"
ng-model="noteText"
placeholder="This is a new note" ></textarea>
<input class="btn btn-outline btn-primary"
type="button"
ng- click="SaveNotes();" value="Save">
</div>
</script>
I have web a page where i have a button and when click the button popover appears.In that popover i have textarea but when i click save button i want get the text in my controller but i am getting undefined using $scope.modelname
How can i get that data?
I think you want to use a modal rather than a popover like so, as a popover is really just to display text :-
var modalInstance = $modal.open({
animation: $rootScope.animationsEnabled,
templateUrl: 'views/myTemplate.html',
size: 'md'
}).result.then(function(result) {
$scope.result = result;
});
This is what it's designed for more info here.

AngularJs - How to use method of one controller in multiple controllers?

I am bit new to AngularJS.
Here is my code:
table.js
.controller('ModalDemoCtrl', function ($scope, $rootScope, $uibModal, $log, tableService) {
$rootScope.$on("openRootDialog", function(event, html){
$scope.openDialog(html);
});
$scope.openDialog = function (html) {
// TODO: replace option dialog with your options:
var modalInstance = $uibModal.open({
animation: true,
templateUrl: html + '.html',
controller: 'ModalInstanceCtrl',
size: 'md',
backdrop: 'static',
keyboard: true,
resolve: {
content: function () {
return $scope.modalContent;
}
}
});
modalInstance.result.then(function (result) {
// Add user in you database
tableService.addUserData(result);
// Add user in your view
$scope.data.push(result)
$scope.tableEdit.reload();
});
}
})
.controller('ModalInstanceCtrl', function ($scope, $modalInstance, content) {
$scope.modalContent = content;
$scope.ok = function () {
$modalInstance.close($scope.user);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
})
//user
.controller('tableUserCtrl', function($scope, $rootScope, $uibModal, $log, $filter, $sce, ngTableParams, tableService) {
//var data = tableService.data;
var selfUser = this;
$scope.data = [];
//selfUser.obj = null;
var promise = tableService.getUserData();
promise.then(
function(payload) {
$scope.data = payload.data;
$scope.tableEdit = new ngTableParams({
page: 1, // show first page
count: 10, // count per page
sorting: {
name: 'asc' // initial sorting
}
}, {
total: $scope.data.length, // length of data
getData: function($defer, params) {
//$defer.resolve(selfUser.data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
//sorting
var orderedData = params.sorting() ? $filter('orderBy')($scope.data, params.orderBy()) : $scope.data;
//filtering
orderedData = params.filter() ? $filter('filter')(orderedData, params.filter()) : orderedData;
//orderedData = orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count());
//params.total(orderedData.length);
//$defer.resolve(orderedData);
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
},
function(errorPayload) {
$log.error('failure loading movie', errorPayload);
});
//to update data
$scope.updateUser = function(w) {
tableService.updateUserData(w);
}
$scope.removeUser = function(id, w) {
tableService.removeUserData(id)
//alert(JSON.stringify($scope.data))
$scope.data.splice($scope.data.indexOf(w), 1);
$scope.tableEdit.reload();
//alert(JSON.stringify($scope.data))
}
$scope.openUserDialog = function(html) {
$rootScope.$emit("openRootDialog", {});
}
})
view.html
<div class="container" data-ng-controller="tableUserCtrl">
<!--<div class="p-t-0" data-ng-controller="ModalDemoCtrl"> -->
<script type="text/ng-template" id="adduser.html">
<div class="modal-header">
<!--<h4 class="modal-title">Add User</h4>-->
</div>
<form role="form" ng-submit="insertInfo(userInfo);" name="userForm" novalidate>
<div class="modal-body m-l-15">
<div class="row">
<div class="form-group fg-float m-b-30">
<div class="fg-line">
<input type="text" class="input-sm form-control fg-input" name="name" ng-model="user.name" required="">
<label class="fg-label">Name</label>
</div>
<div ng-show="userForm.$submitted || userForm.name.$touched">
<div ng-show="userForm.name.$error.required" class="error">This field is required.</div>
</div>
</div>
...
</div>
</div>
<div class="modal-footer">
<button class="btn btn-link" ng-click="ok(user);" ng-disabled="userForm.$invalid">Submit</button>
<button class="btn btn-link" ng-click="cancel()">Cancel</button>
</div>
</form>
</script>
<button class="btn btn-default pull-right" ng-click="openUserDialog('adduser')">Add User</button><br/><br/>
<!--</div>-->
<div class="card">
<div class="card-header">
<h2>Users <small></small></h2>
</div>
<div class="card-body">
<div class="table-responsive">
<table ng-table="tableEdit" class="table table-striped table-vmiddle" show-filter="true">
<tr ng-repeat="w in $data" ng-class="{ 'active': w.$edit }">
<td data-title="'Name'" filter="{ 'name': 'text' }" sortable="'name'">
<span ng-if="!w.$edit">{{ w.name }}</span>
<div ng-if="w.$edit"><input class="form-control" type="text" ng-model="w.name" /></div>
</td>
...
<td data-title="'Actions'">
<button type="button" class="btn btn-default" ng-if="!w.$edit" ng-click="w.$edit = true"><i class="zmdi zmdi-edit"></i></button>
<button type="button" class="btn btn-default" ng-if="!w.$edit" ng-click="removeUser(w.user_id, w)"><i class="zmdi zmdi-close"></i></button>
<button type="button" class="btn btn-success" ng-if="w.$edit" ng-click="w.$edit = false; updateUser(w)"><i class="zmdi zmdi-check"></i></button>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
I am passing html template name in openUserDialog function from view as I need to use that name in openDialog function written in ModalDemoCtrl so I can use dynamic templates in modal.
I have searched a lot but couldn't get exact things that how can I pass args to openRootDialog from openUserDialogfunction written in tableUserCtrl?
can anyone please help me? is there any syntax issue? I don't have any idea about $emit, $on etc. as am using it first time.
Use $rootscope,
this is example:
app.run(function($rootScope) {
$rootScope.someMethod=function(){
//do staff
}
}
in another controller just use $scope.someMethod(), in view someMethod().
it is global method now.

Is there any way to use $uibModal and $uibModalInstance in a single controller to implement modal popup using angular with typescript?

As I am a newbie in angular with typescript I am facing a issue while implemented angular modal popup. The issue is I have one drop-down on which change I have to open a modal popup and that modal popup will have two buttons "Yes" or "No". For this I have one controller where I have injected a dependency.
export class QuestionnaireController {
static ngControllerName = 'questionnaireController';
static inject = ["$uibModal"];
constructor(private $uibModal: ng.ui.bootstrap.IModalService) {
}
public openModalPopup() {
let options: ng.ui.bootstrap.IModalSettings = {
controller: QuestionnaireController,
controllerAs:'ctrl',
templateUrl: 'app/views/Dialogbox.html',
};
this.$uibModal.open(options);
}
}
Most of my code is written in 'QuestionnaireController' and the popup is getting open using this controller but I also want to close this popup so I read a article where it was written that I have to created a new controller "ModalController " to make popup close.
export class ModalController {
static inject = ["$uibModalInstance"];
constructor(private $uibModalInstance: ng.ui.bootstrap.IModalServiceInstance) {
}
public close() {
this.$uibModalInstance.close();
}
}
Popup code is here...
<div ng-app="" id="dvModal">
<div class="modal-header">
</div>
<div class="modal-body">
<p> Evaluated result will be discarded if you continue. Are you sure you want to continue?</p>
</div>
<div class="modal-footer">
<input id="yesBtn" type="button" class="btn btn-default" ng-click="ctrl.Yes('true')" value="Yes" />
<input id="npBtn" type="button" class="btn btn-default" ng-click="ctrl.close()" value="No" />
</div>
and to close this passed Controller : ModalController in options which makes my popup closed on click of "No". But now the issue is generated here, how I again went to "QuestionnaireController" to do "Yes" functionality as "Yes" functionality is written in QuestionnaireController.
Yes, you can!
$uibModal is super flexible tool.
I'm not super familiar with Typescript, but here's my JS solution:
angular
.module('appName', ['ui.bootstrap'])
.controller('SomePageController', ['$scope', '$uibModal', '$log',
function ($scope, $uibModal, $log) {
First you want to do, is to change your openModalPopup() method:
// Instantiate the modal window
var modalPopup = function () {
return $scope.modalInstance = $uibModal.open({
templateUrl: 'blocks/modal/dialog.html',
scope: $scope
});
};
// Modal window popup trigger
$scope.openModalPopup = function () {
modalPopup().result
.then(function (data) {
$scope.handleSuccess(data);
})
.then(null, function (reason) {
$scope.handleDismiss(reason);
});
};
// Close the modal if Yes button click
$scope.yes = function () {
$scope.modalInstance.close('Yes Button Clicked')
};
// Dismiss the modal if No button click
$scope.no = function () {
$scope.modalInstance.dismiss('No Button Clicked')
};
// Log Success message
$scope.handleSuccess = function (data) {
$log.info('Modal closed: ' + data);
};
// Log Dismiss message
$scope.handleDismiss = function (reason) {
$log.info('Modal dismissed: ' + reason);
}
}
]);
Second - modal window HTML template will look like this:
<script type="text/ng-template" id="blocks/modal/dialog.html">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
Modal content
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="yes()">Yes</button>
<button class="btn btn-warning" type="button" ng-click="no()">No</button>
</div>
</script>
Third - pretty simple SomePage HTML (in your case - Questionnaire) View example :
<div ng-controller="SomePageController">
<button type="button" class="btn btn-default" ng-click="openModalPopup()">Open modal</button>
</div>
All together:
angular
.module('appName', ['ui.bootstrap'])
.controller('SomePageController', ['$scope', '$uibModal', '$log',
function($scope, $uibModal, $log) {
$scope.modalPopup = function() {
modal = $uibModal.open({
templateUrl: 'blocks/modal/dialog.html',
scope: $scope
});
$scope.modalInstance = modal;
return modal.result
};
$scope.modalPopupTrigger = function() {
$scope.modalPopup()
.then(function(data) {
$scope.handleSuccess(data);
},function(reason) {
$scope.handleDismiss(reason);
});
};
$scope.yes = function() {
$scope.modalInstance.close('Yes Button Clicked')
};
$scope.no = function() {
$scope.modalInstance.dismiss('No Button Clicked')
};
$scope.handleSuccess = function(data) {
$log.info('Modal closed: ' + data);
};
$scope.handleDismiss = function(reason) {
$log.info('Modal dismissed: ' + reason);
}
}
]);
<!DOCTYPE html>
<html>
<head>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body ng-app="appName">
<div ng-controller="SomePageController">
<script type="text/ng-template" id="blocks/modal/dialog.html">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
Modal content
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="yes()">Yes</button>
<button class="btn btn-warning" type="button" ng-click="no()">No</button>
</div>
</script>
<button type="button" class="btn btn-default" ng-click="modalPopupTrigger()">Open modal</button>
</div>
<script src="https://code.angularjs.org/1.5.7/angular.min.js"></script>
<script src="https://code.angularjs.org/1.5.7/angular-animate.min.js"></script>
<script src="https://raw.githubusercontent.com/angular-ui/bootstrap-bower/master/ui-bootstrap-tpls.min.js"></script>
</body>
</html>
Well, if you are that lazy guy like me, the following will also work ;)
var objects = [{
name: "obj1",
value: 1
}, {
name: "obj2",
value: 2
}];
// Generating the modal html
var html = "<div class='modal-header'><h4 class='modal-title'>Select Object</h4></div>";
html += "<div class='modal-body'>";
html += "<select class='form-control' ng-model='selection'>";
for (var i = 0; i < objects.length; i++) {
var ob = objects[i];
html += "<option value='" + ob.value + "'>" + ob.name + "</option>";
}
html += "</select>";
html += "</div>";
html += "<div class='modal-footer'>";
html += '<button type="button" ng-click="dismissModal()" class="btn btn-default" >Close</button>';
html += '<button type="button" ng-click="closeModal()" class="btn btn-primary">Select</button>';
html += "</div>";
// Showing the modal
var objectSelectionModal = $uibModal.open({
template: html,
controller: function($scope) {
// The function that is called for modal closing (positive button)
$scope.closeModal = function() {
//Closing the model with result
objectSelectionModal.close($scope.selection);
};
//The function that is called for modal dismissal(negative button)
$scope.dismissModal = function() {
objectSelectionModal.dismiss();
};
}
});
//Processing the Result
objectSelectionModal.result.then(function(selected) {
alert(selected);
});

Best way to create a reusable modal window in angularjs

I am using html5, angularjs, bootstrap. So each one of them gives many options to create a modal window. Whole of my website has 2 things, one is confirmation dialog or form dialog. So which is the best reusable approach. Should i use html5 or create a directive ?
As mentioned in the comments ui-bootstrap Modal is very useful.
Just for an example here is a factory for confirm modal that you can extend according to your use case:
yourApp.factory("dialog", ["$modal",
function($modal) {
var dialogService = {
confirm: function(options) {
var modalInstance = $modal.open({
templateUrl: 'partials/confirm-modal.html',
controller: ['$scope',
function($scope) {
$scope.header = options.header;
$scope.body = options.body;
$scope.confirmText = options.confirmText || "Close";
$scope.cancelText = options.cancelText || "Confirm";
$scope.hideCancelButton = options.hideCancelButton;
$scope.cancel = function() {
modalInstance.dismiss('cancel');
};
$scope.confirm = function() {
modalInstance.close();
};
}
]
});
return modalInstance.result;
}
}
}
])
And here is your template:
<div class="modal-header">
<button type="button" data-dismiss="modal" aria-hidden="true" class="btn close" ng-click="cancel()">×</button>
<h4 id="noteLabel" class="modal-title">{{header}}</h4>
</div>
<div class="modal-body">
<p ng-bind-html="body" style="font-size: 16px"></p>
</div>
<div class="modal-footer">
<button ng-show="!hideCancelButton" class="btn btn-default" ng-click="cancel()">{{cancelText}}</button>
<button ng-click="confirm()" class="btn btn-primary">{{confirmText}}</button>
</div>

ng-model not updates inside ng-repeat

The "declineReasonId" variable is not updates. i use $parent to access parent variable inside "ng-repeat" but it still not working.
I have ng-template html:
<script type="text/ng-template" id="boxDeclineReasonPopup.html">
<div class="modal-header">
<h3 class="modal-title">Chose reason</h3>
</div>
<div class="modal-body">
<form>
<div class="form-group reasonPopupLabel">
<div ng-repeat="(key, value) in reasons" ng-if="key != 0">
<label>{{value}}</label>
<input type="radio" class="form-control" name="reason" ng-model="$parent.declineReasonId" ng-value="{{key}}">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-disabled="declineReasonId === '0'" ng-click="ok()">Submit</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
and my controller:
(function () {
function declineReasonModalController($scope, $modalInstance, appData) {
$scope.declineReasonId = '0';
$scope.reasons = appData.report_type;
$scope.ok = function () {
$modalInstance.close($scope.declineReasonId);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
$scope.$watch('declineReasonId', function () {
debugger;
});
}
declineReasonModalController.$inject = ['$scope', '$modalInstance', 'appData'];
var controllers = angular.module('app.controllers');
controllers.controller('DeclineReasonModalController', declineReasonModalController);
})();
The modal instance triggered by function:
$scope.decline = function () {
var modalInstance = $modal.open({
templateUrl: 'boxDeclineReasonPopup.html',
controller: 'DeclineReasonModalController'
});
modalInstance.result.then(function (reasonId) {
$scope.declineReasonId = reasonId;
$scope.declineConfirm();
}, function () { });
};
If i put "{{$parent.declineReasonId }}" inside ng-repeat is duplicate copy of variable. When i press radio button is change value of one of duplicated copies. Why?
The $parent is still not the modal controller's scope yet.
You can use $parent.$parent.declineReasonId to reach the scope in your specific case.
That is why the use of $parent is discouraged.
The best practice when using ng-model is to not reference something in $scope directly, like this:
$scope.model = {};
$scope.model.declineReasonId = '0';
Then change your ng-model this instead:
ng-model="model.declineReasonId"

Resources