I've a bootstrap modal which contains a table of users.
I can select a user from the table and on clicking 'save', the details of seleced user is displayed.
I'm displaying 10 users per page in the table of the modal.
However, if I select any user from page 1 and then click next to select some users from page 2 and click on 'save', my selection from page 1 is not retained.
I mean the checkbox is cleared on page 1, whenever I click on next or previous.
How do I retain this selection on my checkbox, even if I click on next or previous at any page?
Here's the snippet:
var currentPageNo = 0; // Keep track of currently displayed page
// Select button that is descendant of userList
$('#userList .prev-btn').click(function(){
userList(currentPageNo-10);
});
$('#userList .next-btn').click(function(){
userList(currentPageNo+10);
});
$('#adminList .prev-btn').click(function(){
adminList(currentPageNo-10);
});
$('#adminList .next-btn').click(function(){
adminList(currentPageNo+10);
});
function userList(pageNo) {
var resType="userList";
createTable(resType,pageNo);
}
function adminList(pageNo) {
var resType="adminList";
createTable(resType,pageNo);
}
function createTable(resType, pageNo) {
// Update global variable
currentPageNo = pageNo;
// Set visibility of the correct "prev" button:
$('#' + resType + ' .prev-btn').toggle(pageNo > 0);
// Ask one record more than needed, to determine if there are more records after this page:
$.getJSON("https://api.randomuser.me/?results=11&resType="+resType + "&pageIndex=" + pageNo, function(data) {
var $table = $('#' + resType + ' table');
$('tr:has(td)', $table).empty();
// Check if there's an extra record which we do not display,
// but determines that there is a next page
$('#' + resType + ' .next-btn').toggle(data.results.length > 10);
// Slice results, so 11th record is not included:
data.results.slice(0, 10).forEach(function (record, i) { // add second argument for numbering records
var json = JSON.stringify(record);
$table.append(
$('<tr>').append(
$('<td>').append(
$('<input>').attr('type', 'checkbox')
.addClass('selectRow')
.val(json),
(i+1+pageNo) // display row number
),
$('<td>').append(
$('<a>').attr('href', record.picture.thumbnail)
.addClass('imgurl')
.attr('target', '_blank')
.text(record.name.first)
),
$('<td>').append(record.dob)
)
);
});
// Show the prev and/or buttons
}).fail(function(error) {
console.log("**********AJAX ERROR: " + error);
});
}
var savedData = []; // The objects as array, so to have an order.
function saveData(){
var errors = [];
// Add selected to map
$('input.selectRow:checked').each(function(count) {
// Get the JSON that is stored as value for the checkbox
var obj = JSON.parse($(this).val());
// See if this URL was already collected (that's easy with Set)
if (savedData.find(record => record.picture.thumbnail === obj.picture.thumbnail)) {
errors.push(obj.name.first);
} else {
// Append it
savedData.push(obj);
}
});
refreshDisplay();
if (errors.length) {
alert('The following were already selected:\n' + errors.join('\n'));
}
}
function refreshDisplay() {
$('.container').html('');
savedData.forEach(function (obj) {
// Reset container, and append collected data (use jQuery for appending)
$('.container').append(
$('<div>').addClass('parent').append(
$('<label>').addClass('dataLabel').text('Name: '),
obj.name.first + ' ' + obj.name.last,
$('<br>'), // line-break between name & pic
$('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'),
$('<label>').addClass('dataLabel').text('Date of birth: '),
obj.dob, $('<br>'),
$('<label>').addClass('dataLabel').text('Address: '), $('<br>'),
obj.location.street, $('<br>'),
obj.location.city + ' ' + obj.location.postcode, $('<br>'),
obj.location.state, $('<br>'),
$('<button>').addClass('removeMe').text('Delete'),
$('<button>').addClass('top-btn').text('Swap with top'),
$('<button>').addClass('down-btn').text('Swap with down')
)
);
})
// Clear checkboxes:
$('.selectRow').prop('checked', false);
handleEvents();
}
function logSavedData(){
// Convert to JSON and log to console. You would instead post it
// to some URL, or save it to localStorage.
console.log(JSON.stringify(savedData, null, 2));
}
function getIndex(elem) {
return $(elem).parent('.parent').index();
}
$(document).on('click', '.removeMe', function() {
// Delete this from the saved Data
savedData.splice(getIndex(this), 1);
// And redisplay
refreshDisplay();
});
/* Swapping the displayed articles in the result list */
$(document).on('click', ".down-btn", function() {
var index = getIndex(this);
// Swap in memory
savedData.splice(index, 2, savedData[index+1], savedData[index]);
// And redisplay
refreshDisplay();
});
$(document).on('click', ".top-btn", function() {
var index = getIndex(this);
// Swap in memory
savedData.splice(index-1, 2, savedData[index], savedData[index-1]);
// And redisplay
refreshDisplay();
});
/* Disable top & down buttons for the first and the last article respectively in the result list */
function handleEvents() {
$(".top-btn, .down-btn").prop("disabled", false).show();
$(".parent:first").find(".top-btn").prop("disabled", true).hide();
$(".parent:last").find(".down-btn").prop("disabled", true).hide();
}
$(document).ready(function(){
$('#showExtForm-btn').click(function(){
$('#extUser').toggle();
});
$("#extUserForm").submit(function(e){
addExtUser();
return false;
});
});
function addExtUser() {
var extObj = {
name: {
title: "mr", // No ladies? :-)
first: $("#name").val(),
// Last name ?
},
dob: $("#dob").val(),
picture: {
thumbnail: $("#myImg").val()
},
location: { // maybe also ask for this info?
}
};
savedData.push(extObj);
refreshDisplay(); // Will show some undefined stuff (location...)
}
.parent {
background-color: #0000FF;
color: white;
border: 1px solid black;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#userList" onclick="userList(0)">User List</button>
<button class="btn btn-primary btn-sm" onclick="logSavedData()">Get Saved Data</button>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#adminList" onclick="adminList(0)">User Admin</button>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#extUser">Open External Form</button>
<div class="modal fade" id="userList" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">User List</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-bordered table-hover" id="datatable">
<tr>
<th>Select</th>
<th>Name</th>
<th>DOB</th>
</tr>
</table>
</div>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary prev-btn"><span class="glyphicon glyphicon-chevron-left"></span></button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary next-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
</div>
</div>
<hr/>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary btn-sm" onclick="saveData()">Save selected</button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary btn-sm close-less-modal" data-dismiss="modal">Close</button>
</div>
</div>
<br />
</div>
</div>
</div>
</div>
<div class="modal fade" id="adminList" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Admin List</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-bordered table-hover" id="datatable">
<tr>
<th>Select</th>
<th>Name</th>
<th>DOB</th>
</tr>
</table>
</div>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary prev-btn"><span class="glyphicon glyphicon-chevron-left"></span></button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary next-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
</div>
</div>
<hr/>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary btn-sm" onclick="saveData()">Save selected</button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary btn-sm close-less-modal" data-dismiss="modal">Close</button>
</div>
</div>
<br />
</div>
</div>
</div>
</div>
<div class="modal fade" id="extUser" role="dialog">
<div class="modal-dialog modal-lg">
<!-- External User-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add External User</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" id="extUserForm">
<div class="form-group">
<label class="control-label col-sm-3" for="name">Name:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="name" name="name" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="myImg">Image:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="myImg" name="myImg" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="dob">DOB:</label>
<div class="col-sm-8">
<input type="date" class="form-control" id="dob" name="dob" required>
</div>
</div>
<hr />
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
<button class="btn btn-primary btn-sm">Submit</button>
</div>
<div class="col-sm-3">
<button type="reset" class="btn btn-primary btn-sm">Reset</button>
</div>
<div class="col-sm-3">
<button type="button" class="btn btn-primary btn-sm close-external-modal" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="container"></div>
If you want the checkboxes to persist even when you move to another page, I would suggest that you actually keep those rows with checkboxes, but just hide them when moving to the next page.
The idea is that you never remove rows, but only add them when moving to a page you had not yet visited. But when going back to previous pages, you just make those 10 rows visible, and hide all others. That way you will even have a better user-experience, since those pages do not have to be requested from the server any more.
To achieve this, you just have to make a few changes in the first few lines of the creatTable function:
function createTable(resType, pageNo) {
// Update global variable
currentPageNo = pageNo;
// Set visibility of the correct "prev" button:
$('#' + resType + ' .prev-btn').toggle(pageNo > 0);
// *** See if we have that page already loaded
var $table = $('#' + resType + ' table');
// *** Count the rows already in the table, to see if we already have the page
var lastPageNo = $('tr:has(td)', $table).length - 1;
if (currentPageNo < lastPageNo) {
// *** We have the page: hide all rows, except those of that page
$('tr:has(td)', $table).hide().slice(currentPageNo, currentPageNo+10).show();
return;
}
// Otherwise make the request.
// Ask one record more than needed, to determine if there are more records after this page:
$.getJSON("https://api.randomuser.me/?results=11&resType="+resType + "&pageIndex=" + pageNo, function(data) {
//*** don't clear the table, but hide all rows, so they can be reused when paging back
$('tr:has(td)', $table).hide();
// Check if there's an extra record which we do not display,
// but determines that there is a next page
$('#' + resType + ' .next-btn').toggle(data.results.length > 10);
// ...etc ... etc
Here is the whole snippet:
var currentPageNo = 0; // Keep track of currently displayed page
// Select button that is descendant of userList
$('#userList .prev-btn').click(function(){
userList(currentPageNo-10);
});
$('#userList .next-btn').click(function(){
userList(currentPageNo+10);
});
$('#adminList .prev-btn').click(function(){
adminList(currentPageNo-10);
});
$('#adminList .next-btn').click(function(){
adminList(currentPageNo+10);
});
function userList(pageNo) {
var resType="userList";
createTable(resType,pageNo);
}
function adminList(pageNo) {
var resType="adminList";
createTable(resType,pageNo);
}
function createTable(resType, pageNo) {
// Update global variable
currentPageNo = pageNo;
// Set visibility of the correct "prev" button:
$('#' + resType + ' .prev-btn').toggle(pageNo > 0);
// *** See if we have that page already loaded
var $table = $('#' + resType + ' table');
// *** Count the rows already in the table, to see if we already have the page
var lastPageNo = $('tr:has(td)', $table).length - 1;
if (currentPageNo < lastPageNo) {
// *** We have the page: hide all rows, except those of that page
$('tr:has(td)', $table).hide().slice(currentPageNo, currentPageNo+10).show();
return;
}
// Otherwise make the request.
// Ask one record more than needed, to determine if there are more records after this page:
$.getJSON("https://api.randomuser.me/?results=11&resType="+resType + "&pageIndex=" + pageNo, function(data) {
//*** don't clear the table, but hide all rows, so they can be reused when paging back
$('tr:has(td)', $table).hide();
// Check if there's an extra record which we do not display,
// but determines that there is a next page
$('#' + resType + ' .next-btn').toggle(data.results.length > 10);
// Slice results, so 11th record is not included:
data.results.slice(0, 10).forEach(function (record, i) { // add second argument for numbering records
var json = JSON.stringify(record);
$table.append(
$('<tr>').append(
$('<td>').append(
$('<input>').attr('type', 'checkbox')
.addClass('selectRow')
.val(json),
(i+1+pageNo) // display row number
),
$('<td>').append(
$('<a>').attr('href', record.picture.thumbnail)
.addClass('imgurl')
.attr('target', '_blank')
.text(record.name.first)
),
$('<td>').append(record.dob)
)
);
});
}).fail(function(error) {
console.log("**********AJAX ERROR: " + error);
});
}
var savedData = []; // The objects as array, so to have an order.
function saveData(){
var errors = [];
// Add selected to map
$('input.selectRow:checked').each(function(count) {
// Get the JSON that is stored as value for the checkbox
var obj = JSON.parse($(this).val());
// See if this URL was already collected (that's easy with Set)
if (savedData.find(record => record.picture.thumbnail === obj.picture.thumbnail)) {
errors.push(obj.name.first);
} else {
// Append it
savedData.push(obj);
}
});
refreshDisplay();
if (errors.length) {
alert('The following were already selected:\n' + errors.join('\n'));
}
}
function refreshDisplay() {
$('.container').html('');
savedData.forEach(function (obj) {
// Reset container, and append collected data (use jQuery for appending)
$('.container').append(
$('<div>').addClass('parent').append(
$('<label>').addClass('dataLabel').text('Name: '),
obj.name.first + ' ' + obj.name.last,
$('<br>'), // line-break between name & pic
$('<img>').addClass('myLink').attr('src', obj.picture.thumbnail), $('<br>'),
$('<label>').addClass('dataLabel').text('Date of birth: '),
obj.dob, $('<br>'),
$('<label>').addClass('dataLabel').text('Address: '), $('<br>'),
obj.location.street, $('<br>'),
obj.location.city + ' ' + obj.location.postcode, $('<br>'),
obj.location.state, $('<br>'),
$('<button>').addClass('removeMe').text('Delete'),
$('<button>').addClass('top-btn').text('Swap with top'),
$('<button>').addClass('down-btn').text('Swap with down')
)
);
})
// Clear checkboxes:
$('.selectRow').prop('checked', false);
handleEvents();
}
function logSavedData(){
// Convert to JSON and log to console. You would instead post it
// to some URL, or save it to localStorage.
console.log(JSON.stringify(savedData, null, 2));
}
function getIndex(elem) {
return $(elem).parent('.parent').index();
}
$(document).on('click', '.removeMe', function() {
// Delete this from the saved Data
savedData.splice(getIndex(this), 1);
// And redisplay
refreshDisplay();
});
/* Swapping the displayed articles in the result list */
$(document).on('click', ".down-btn", function() {
var index = getIndex(this);
// Swap in memory
savedData.splice(index, 2, savedData[index+1], savedData[index]);
// And redisplay
refreshDisplay();
});
$(document).on('click', ".top-btn", function() {
var index = getIndex(this);
// Swap in memory
savedData.splice(index-1, 2, savedData[index], savedData[index-1]);
// And redisplay
refreshDisplay();
});
/* Disable top & down buttons for the first and the last article respectively in the result list */
function handleEvents() {
$(".top-btn, .down-btn").prop("disabled", false).show();
$(".parent:first").find(".top-btn").prop("disabled", true).hide();
$(".parent:last").find(".down-btn").prop("disabled", true).hide();
}
$(document).ready(function(){
$('#showExtForm-btn').click(function(){
$('#extUser').toggle();
});
$("#extUserForm").submit(function(e){
addExtUser();
return false;
});
});
function addExtUser() {
var extObj = {
name: {
title: "mr", // No ladies? :-)
first: $("#name").val(),
// Last name ?
},
dob: $("#dob").val(),
picture: {
thumbnail: $("#myImg").val()
},
location: { // maybe also ask for this info?
}
};
savedData.push(extObj);
refreshDisplay(); // Will show some undefined stuff (location...)
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#userList" onclick="userList(0)">User List</button>
<button class="btn btn-primary btn-sm" onclick="logSavedData()">Get Saved Data</button>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#adminList" onclick="adminList(0)">User Admin</button>
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#extUser">Open External Form</button>
<div class="modal fade" id="userList" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">User List</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-bordered table-hover" id="datatable">
<tr>
<th>Select</th>
<th>Name</th>
<th>DOB</th>
</tr>
</table>
</div>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary prev-btn"><span class="glyphicon glyphicon-chevron-left"></span></button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary next-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
</div>
</div>
<hr/>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary btn-sm" onclick="saveData()">Save selected</button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary btn-sm close-less-modal" data-dismiss="modal">Close</button>
</div>
</div>
<br />
</div>
</div>
</div>
</div>
<div class="modal fade" id="adminList" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Admin List</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-bordered table-hover" id="datatable">
<tr>
<th>Select</th>
<th>Name</th>
<th>DOB</th>
</tr>
</table>
</div>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary prev-btn"><span class="glyphicon glyphicon-chevron-left"></span></button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary next-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
</div>
</div>
<hr/>
<div class="row">
<div class="col-sm-offset-3 col-sm-4">
<button type="button" class="btn btn-primary btn-sm" onclick="saveData()">Save selected</button>
</div>
<div class="col-sm-4">
<button type="button" class="btn btn-primary btn-sm close-less-modal" data-dismiss="modal">Close</button>
</div>
</div>
<br />
</div>
</div>
</div>
</div>
<div class="modal fade" id="extUser" role="dialog">
<div class="modal-dialog modal-lg">
<!-- External User-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add External User</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" id="extUserForm">
<div class="form-group">
<label class="control-label col-sm-3" for="name">Name:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="name" name="name" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="myImg">Image:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="myImg" name="myImg" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="dob">DOB:</label>
<div class="col-sm-8">
<input type="date" class="form-control" id="dob" name="dob" required>
</div>
</div>
<hr />
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
<button class="btn btn-primary btn-sm">Submit</button>
</div>
<div class="col-sm-3">
<button type="reset" class="btn btn-primary btn-sm">Reset</button>
</div>
<div class="col-sm-3">
<button type="button" class="btn btn-primary btn-sm close-external-modal" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="container"></div>
I'm trying to add a modal popup window to my Angular app. Although it lists down the names, when I click on the names a modal doesn't appear. Below is my code
HTML:
<div ng-app="app">
<div ng-repeat="customer in customers">
<button class="btn btn-default" ng-click="open(customer)">{{ customer.name }}</button> <br />
<!--MODAL WINDOW-->
<script type="text/ng-template" id="myContent.html">
<div class="modal-header">
<h3>The Customer Name is: {{ customer.name }}</h3>
</div>
<div class="modal-body">
This is where the Customer Details Goes<br />
{{ customer.details }}
</div>
<div class="modal-footer">
</div>
</script>
</div>
</div>
JS:
var app = angular.module('app', ['ngRoute','ui.bootstrap']);
app.config(function($routeProvider) {
$routeProvider.
when('/', {controller:testcontroller, templateUrl:'http://localhost/app/index.php/customer/home'}).
otherwise({redirectTo:'/error'});
});
function test2controller ($scope, $modalInstance, customer) {
$scope.customer = customer;
}
function testcontroller ( $scope, $timeout, $modal, $log) {
$scope.customers = [
{
name: 'Ben',
details: 'Some Details for Ben',
},
{
name: 'Donald',
details: 'Some Donald Details',
},
{
name: 'Micky',
details: 'Some Micky Details',
}
];
$scope.open = function (_customer) {
var modalInstance = $modal.open({
controller: "test2controller",
templateUrl: 'myContent.html',
resolve: {
customer: function()
{
return _customer;
}
}
});
};
}
Can someone let me know what am I doing wrong here?
Controller
$scope.saveFeed = function(feed){
$('#exampleModalCenter').modal('show');
console.log(feed);
}
HTML
<a class="dropdown-item p-3" href="#" ng-click="saveFeed(feed.id)">
<div class="d-flex align-items-top">
<div class="icon font-size-20"><i class="ri-save-line"></i>
</div>
<div class="data ml-2">
<h6>Save Post</h6>
<p class="mb-0">Add this to your saved items</p>
</div>
</div>
</a>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
I think i have some pretty big holes in my code, as when the modal is appearing, the content from the table (which when you click on a row produces the modal), is not populating the input boxes I have inside of the modal. I think I'm tackling the situation in the wrong way and some direction would be fantastic.
My JS:
var app = angular.module('peopleInformation', ['ngAnimate','ui.bootstrap']);
app.controller('myCtrl', function($scope, $http, $uibModal) {
$http.get("Assignment005.json").success(function(response){
$scope.myData = response.People;
});
$scope.modify = function(currentData){
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'myModalContent.html',
controller:function($scope, $uibModalInstance, details){
$scope.FirstName = details.FirstName;
$scope.LastName = details.LastName;
$scope.Age = details.Age;
$scope.Nickname = details.Nickname;
$scope.update = function () {
$uibModalInstance.dismiss('cancel');
};
},
size: 'lg',
resolve: {
details: function() {
return currentData;
}
}
});
};
});
My modal:
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Your row of data</h4>
</div>
<div class="modal-body" name="modelData" style="height:200px">
<form class="form-horizontal pull-left form-width" role="form">
<div class="form-group">
<label class="control-label col-sm-4" for="first">First Name:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="first" ng-model="FirstName">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="last">Last Name:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="last" ng-model="LastName">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="age">Age:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="age" ng-model="Age">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="nick">Nickname:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="nick" ng-model="Nickname">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger pull-left" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-success pull-right" data-dismiss="modal">Submit</button>
</div>
</div>
Main HTML in case it's needed:
<body>
<div data-ng-app="peopleInformation" data-ng-controller="myCtrl" class="jumbotron">
<div class="panel panel-default">
<div class="panel-heading">Essential Information</div>
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Nickname</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="details in myData" data-ng-click="modify(details)">
<td>{{ details.FirstName }}</td>
<td>{{ details.LastName }}</td>
<td>{{ details.Age }}</td>
<td>{{ details.Nickname }}</td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-info pull-right" data-ng-click="new()">Add
</button>
</div>
</div>
<div ng-include="myModalContent.html"></div>
</div>
</body>
Im very new to using Angular so if you could be overtly simple with me that would help to clarify things, although again, any help is appreciated.
Bellow is the angular modal instance controller
app.controller('ModalInstanceCtrl', function ($scope,
$uibModalInstance, item) {
$scope.customer = item;
$scope.yes = function () {
$uibModalInstance.close(); };
$scope.no = function () {
$uibModalInstance.dismiss('cancel');
};
});
bellow is the code for call angular modal
$scope.open = function (item) {
var modalInstance = $uibModal.open({
animation: true,
scope: $scope,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: 'md',
resolve: {
item: function () {
return item;
}
}
});
modalInstance.result.then(function (selectedItem) {
$log.info(selectedItem);
});
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
Bellow is code for template
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">Re-calculate retail price</h3>
</div>
<div class="modal-body">
Margin percent of selected customer is <b>{{ customer.margin_percent }}</b> <br />
Do you want to recalculate the retail price?
</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>
I was actually assigning the values in the wrong place I believe. I moved the:
$scope.FirstName = details.FirstName;
Outside of the var modalInstance variable, and they are now populating the input boxes. If this is messy or not standard then let me know as sometimes the right result is not always the right method. Thanks for those that tried to help, much appreciated.
In your HTML file you are passing different parameter to modify function, It should be equal to the parameter specified in ng-repeat directive.
So in this case this:
<tr data-ng-repeat="data in myData" data-ng-click="modify(details)">
will become:
<tr data-ng-repeat="details in myData" data-ng-click="modify(details)">
I created a custom directive that has event handler on it and use it 3 times.
<div sl-entity-browser btn_label="Browse supplier" handler="supplier_selection_handler(entity)" />
<div sl-entity-browser btn_label="Browse checker" handler="checker_selection_handler(entity)" />
<div sl-entity-browser btn_label="Browse approving officer" handler="approvar_selection_handler(entity)" />
In my controller:
$scope.supplier_selection_handler = function(entity){
$scope.selectedSupplier = entity;
}
$scope.checker_selection_handler = function(entity){
$scope.selectedChecker = entity;
}
$scope.approvar_selection_handler = function(entity){
$scope.selectedApprovingOfficer = entity;
}
My directive:
return {
scope : {
btnLabel : '#',
handler: '&'
},
restrict: 'AE',
templateUrl: '/common/sl-entity-browser',
link: function (scope, elem, attrs) {
// expose selected account to the outside world
scope.selectEntity = function(entity) {
return $timeout(function() {
return scope.handler({
entity: entity
});
});
}
}
};
HTML template:
<button title="browse account" class="btn btn-primary" data-toggle="modal" data-target="#slEntityModal"> {{ btnLabel }}</button>
<div class="modal fade" id="slEntityModal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" style="width: 90%">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Browse entities</h4>
</div>
<div class="modal-body">
<div>
<div class="row">
<div class="input-group pull-right" style="width: 300px">
<input class="form-control" placeholder="Search" ng-model="query" />
<span class="input-group-addon"><i class="glyphicon glyphicon-search"></i></span>
</div>
</div>
<div class="row">
<div class="col-lg-12 col-md-12">
<div class="row-top-buffer" style="margin-top: 15px"/>
<div class='row' style="border-top: 1px solid #dcdcdc; padding-top: 10px">
<div class="col-md-1 col-lg-1"><span style="font-weight: bold; padding-left: 2px;">Acct No</span></div>
<div class="col-md-5 col-lg-5"><span style="font-weight: bold; padding-left: 30px;">Name</span></div>
<div class="col-md-6 col-lg-6"><span style="font-weight: bold">Address</span></div>
</div>
<div class="row-top-buffer" style="margin-top: 5px"/>
<div class="row" style='max-height: 500px; overflow: auto;'>
<div ng-show="!slEntities">Loading entities...</div>
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
</tr>
</thead>
<tbody>
<tr data-dismiss="modal" ng-repeat="entity in entities = (slEntities | filter:query)" style="cursor: pointer" ng-click="selectEntity(entity)">
<td style="width: 100px;">{{entity.accountNo}}</td>
<td style="width: 480px;">{{entity.name}} <span class="label {{entityClass(entity.marker)}} pull-right">{{convert(entity.marker)}}</span></td>
<td>{{entity.address}}</td>
</tr>
<tr ng-show="entities.length == 0"><td colspan="3" align="center">No records found</td></tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The directive will render a button that will display a modal when clicked. The modal contains a table of items. If a certain item is selected, the modal will be disposed and the event should trigger the correct one as defined. The problem is that the first directive instance' event handler (supplier_selection_handler) is always called.
I am new to AngularsJs.
Thanks in advance.
This is because the modal opened by your directives (all of them!) is the first directive's modal. Notice that all your modals share the same ID? and the data-target of your buttons share the same ID? Since an ID of an element is unique, then once an element with that specific ID is found, it'll stop searching for another element with such ID. Thus, all your buttons that opens a modal simply opens the first modal.
I recommend that you use angular-bootstrap's modal instead, the component itself runs in the AngularJS context so no scoping problems may occur.
The example below shows how to create a directive that can makes use of angular-bootstrap's modal, I trimmed down the code below to simplify the demo.
DEMO
INDEX
<body ng-controller="Ctrl">
<button sl-entity-browser
btn-label="hello world"
handler="messageHandler('This is a message from hello world')"
class="btn btn-primary">
Hello World?
</button>
<button sl-entity-browser
btn-label="Yeah Baby"
handler="messageHandler('WEEEE wOoOoOw')"
class="btn btn-primary">
Baby?
</button>
<button sl-entity-browser
btn-label="Boom!"
handler="messageHandler('This is kaboom boom!')"
class="btn btn-primary">Kaboom!</button>
</body>
MODAL
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
{{ btnLabel }}
</div>
<div class="modal-footer">
<button
ng-click="handler()"
class="btn btn-primary pull-left">
Click ME!
</button>
</div>
JAVASCRIPT
(function(angular) {
var app = angular.module('app', ['ui.bootstrap']);
app.controller('Ctrl', function($scope, $window) {
// handler function
$scope.messageHandler = function(message) {
$window.alert(message);
};
});
// directive assignment
app.directive('slEntityBrowser', slEntityBrowser);
function slEntityBrowser() {
// directive definition
return {
scope: {
btnLabel: '#',
handler: '&'
},
controller: slEntityBrowserController,
link: slEntityBrowserLink
};
}
// directive controller
function slEntityBrowserController($scope, $modal) {
// create open() method
// to open a modal
$scope.open = function() {
$modal.open({
scope: $scope,
templateUrl: 'sl-entity-browser-modal.html'
});
};
}
// directive link
function slEntityBrowserLink(scope, elem) {
// register click handler on the current element
// to open the modal
elem.on('click', function() {
scope.open();
});
}
})(window.angular);
I have created a modal that opens another modal. I want to use the second modal as a confirmation box to close the first one. I cant get it to close both modals when I click ok on the confirmation box (the second modal).
Tree.html:
<script type="text/ng-template" id="tree_item_renderer.html">
<div class="bracket-match" ng-class="match.tier == 1 ? 'bracket-match-final' : ''">
<p ng-show="match.tier == 1" class="finale-title">Finale</p>
<div class="match-content">
<div class="player-div">
<div class="bracket-player-1 bracket-player-1-tier-{{tierCount+1-match.tier}}">
<input class="input-player-1 input-player-name form-control" type="text" ng-model="match.player1" placeholder="Deltager 1">
</div>
</div>
<div class="player-div border-bottom">
<div class="bracket-player-2">
<input class="input-player-2 input-player-name form-control" type="text" ng-model="match.player2" placeholder="Deltager 2">
</div>
</div>
</div>
<div ng-show="match.tier == 1 && showthirdplace && tierCount >= 2" class="third-place" ng-model="thirdplace">
<p class="finale-title">3. plads</p>
<div class="match-content">
<div class="player-div">
<div class="bracket-player-1 bracket-player-1-tier-{{tierCount+1-match.tier}}">
<input class="input-player-1 input-player-name form-control" type="text" ng-model="match.player1" placeholder="Deltager 1">
</div>
</div>
<div class="player-div border-bottom">
<div class="bracket-player-2">
<input class="input-player-2 input-player-name form-control" type="text" ng-model="match.player2" placeholder="Deltager 2">
</div>
</div>
</div>
</div>
</div>
<div class="bracket-column">
<div ng-repeat="match in match.previousMatches" ng-include="'tree_item_renderer.html'" />
</div>
</script>
<script type="text/ng-template" id="tournament-tree.html">
<div class="row modal-footer-btns">
<button class="btn btn-primary" ng-click="ok()">GEM</button>
<button class="btn btn-warning btn-xs" ng-click="openAlertBox()" type="button" data-dismiss="modal">LUK, uden at gemme</button>
</div>
<div class="row" style="margin-bottom:15px;">
<a ng-click="addMatchTier()" class="btn btn-primary"><i class="glyphicon glyphicon-plus"></i></a>
<a ng-click="removeMatchTier()" ng-class="tierCount > 1 ? 'btn btn-primary' : 'btn btn-default'"><i class="glyphicon glyphicon-minus"></i></a><br />
</div>
<div class="row tournament-tree">
<div ng-repeat="match in finalMatch">
</div>
<div class="bracket-column">
<div ng-repeat="match in finalMatch" ng-include="'tree_item_renderer.html'"></div>
</div>
</div>
</script>
<script type="text/ng-template" id="openAlertBox.html">
<div class="modal-header">
<h3 class="modal-title"></h3>
</div>
<div class="modal-body"> </div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">Ja</button>
<button class="btn btn-warning" ng-click="cancel()">Annuller</button>
</div>
</script>
Categories.html:
<div class="row">
<div class="modal-header">
<h3 class="modal-title"></h3>
</div>
</div>
<div ng-controller="CategoriesController">
<a ng-click="add()" class="btn btn-tree btn-primary" style="margin-top:15px;">Tilføj hovedkategori</a>
<p ng-repeat="data in nodes" ng-include="'category_item_renderer.html'"></p>
<ng-include src="'Modules/TournamentTree/Tree.html'"></ng-include>
</div>
<script type="text/ng-template" id="category_item_renderer.html">
<div class="category-style">
<div class="push-cat-btn">
<a ng-click="add(data)" class="btn btn-primary btn-sm"><i class="glyphicon glyphicon glyphicon-plus"></i></a>
<a ng-hide="data.nodes.push()" ng-click="openTournamentTree(data)" class="btn btn-info btn-xs">Turnering</a>
</div>
</div>
<p class="push" ng-repeat="data in data.nodes" ng-include="'category_item_renderer.html'"></p>
</script>
<script type="text/ng-template" id="TournamentTreeModal.html">
<div class="modal-header">
<h3 class="modal-title"></h3>
</div>
<div class="modal-body">
<div class="include-tree" ng-include="'tournament-tree.html'"></div>
</div>
<div class="modal-footer">
</div>
</script>
TreeController.js:
angular.module('tournamentTree', ['ui.bootstrap']);
angular.module('tournamentTree').controller("TreeController", ['$scope', '$modal', '$modalInstance', 'guidGenerator', function ($scope, $modal, $modalInstance, guidGenerator) {
$scope.openAlertBox = function () {
var alertBoxInstance = $modal.open({
templateUrl: 'openAlertBox.html',
controller: 'TreeController',
scope: $scope,
size: 'xs',
resolve: {
}
});
};
$scope.ok = function () {
$scope.close();
$scope.$parent.close();
}
$scope.cancel = function () {
$scope.close();
$scope.$parent.dismiss('cancel');
};
categoriController.js:
angular.module('tournamentCategories').controller("CategoriesController",
['$scope', '$modal', 'guidGenerator', 'eventBus', domainName + "Service", 'TournamentCategoryModelFactory',
function ($scope, $modal, guidGenerator, eventBus, domainService, modelFactory) {
$scope.openTournamentTree = function () {
var modalInstance = $modal.open({
templateUrl: 'TournamentTreeModal.html',
controller: 'TreeController',
scope: $scope,
size: 'wide-90',
backdrop: 'static',
keyboard: false,
resolve: {
}
});
modalInstance.result.then(function (selectedItem) {
//$scope.selected = selectedItem;
}, function () {
//$log.info('Modal dismissed at: ' + new Date());
});
};
}]);
You can use $modalStack from ui.bootstrap to close all instances of $modalInstance
$modalStack.dismissAll(reason);
This is how i got it working in my project without using any factory or additional code.
//hide any open bootstrap modals
angular.element('.inmodal').hide();
I have a timeout function that emits logout as $rootScope.$emit('logout'); and the listener in my service is as follows:
$rootScope.$on('logout', function () {
//hide any open bootstrap modals
angular.element('.inmodal').hide();
//do something else here
});
If you want to hide any other modals such as angular material dialog ($mdDialog) & sweet alert dialog's use angular.element('.modal-dialog').hide(); & angular.element('.sweet-alert').hide();
I don't know if this is the right approach , but it works for me.