Pass object outside of ng-repeat - javascript

So I'm new to AngularJs. Currently I'm trying to implement a table filtering and then when I click on the delete button it should delete the right object.
this is how I did it before filtering :
$scope.rowIndex = -1;
$scope.selectRow = function(index) {
if (index == $scope.rowIndex)
$scope.rowIndex = -1;
else
$scope.rowIndex = index;
}
});
In my html :
ng-repeat="session in sessons " ng-class="{'bg-primary':rowIndex == $index }" ng-click="selectRow($index)"
Now after implementing filtering I found out that $index is wrong... So I had to find another way.. I read some articles and all said the same... I just could pass the whole object to the function... But every example did it inside the ng-repeat. Unfortunately... I can't do that since I've a external div for the Modal.
So how do I pass the current selected session / row of the table to the function which is in the modal? {{ deleteSession(session) }}
<div id="deleteSessionModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form>
<div class="modal-header">
<h4 class="modal-title">Delete Session</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p>Are you sure you want to delete these Records?</p>
<p class="text-warning">
<small>This action cannot be undone.</small>
</p>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
<input type="submit" class="btn btn-danger" value="Delete" ng-click="deleteSession(session)">
</div>
</form>
</div>
</div>
</div>
this is how my html / table looks like

you can pass the session as the value to select row function like that:
ng-repeat="session in sessons " ng-class="{'bg-primary':rowIndex == $index }" ng-click="selectRow(session)"
and in the function selectRow, you can take the Id from the session and delete it from the sessions list.

Instead of passing $index to selectRow function, send session.speakerId or another specific unique key of sessions:
ng-click="selectRow(session.speakerId)"
In your controller set/unset selected session:
$scope.selectedSessionSpeakerId = null;
$scope.selectRow = function(sess) {
if (sess == $scope.selectedSessionSpeakerId)
$scope.selectedSessionSpeakerId = null;
else
$scope.selectedSessionSpeakerId = sess;
}
And your deleteSession function does not receive any arguments. It just check the selected Session unique key and delete that from array:
$scope.deleteSession = function() {
if($scope.selectedSessionSpeakerId) {
let index = $scope.sessions.findIndex(finction(itm) {
return itm["speakerId"] == $scope.selectedSessionSpeakerId;
});
$scope.sessions.splice(index, 1);
$scope.selectedSessionSpeakerId = null;
}
}

Related

Update asp-route-id with jQuery

I'm building a razor pages application, and I want to use a modal as a partial view.
Foreach loop from where I'm opening the modal:
#foreach (var item in Model.SourceFiles)
{
<tr>
<td>#item.Id</td>
<td>#item.FileName</td>
<td>#item.Created</td>
<td>
#(item.IsConverted == true ? "Exported" : "Imported")
</td>
<td>
<button type="submit" class="btn btn-primary" asp-page-handler="FileContent" asp-route-fileId="#item.Id">View</button>
</td>
<td>
#if ((await authorizationService.AuthorizeAsync(User, "DeletePolicy")).Succeeded)
{
Delete
}
</td>
</tr>
}
I'm trying to set a new value of an asp-route-id tag using javaScript (jQuery), but I cant get it to work.
function triggerDeleteModal(itemId) {
$('#' + 'deleteModal').modal('toggle');
$("#confirmDeleteButton").attr('asp-route-deleteid', itemId)
}
Modal (partial view):
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalTitle" 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="deleteModalTitle">Caution!</h5>
</div>
<div class="modal-body">
<p style="white-space: pre-wrap;">#Model.DeleteModalText</p>
<p></p>
</div>
<div class="modal-footer">
<button type="submit" id="confirmDeleteButton" class="btn btn-secondary" data-bs-dismiss="modal">Yes</button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
When pressing the yes-button (#confirmDeleteButton) in the modal to submit the form, the id is not getting passed in the asp-route-deleteid tag helper, and the id is always 0 in the OnPost-method.
Code behind where deleteid always is 0:
public async Task<IActionResult> OnPostAsync(int deleteid)
{
//code for deleting stuff
}
When trying to console.log the value of any attribute besides asp-route tags, the value is shown. When trying to log the value of an asp-route tag, the value is undefined.
Any ideas of how I can get the asp-route-deleteid to be passed to the code behind?
BR
The asp-route-* attribute works on tag helpers, which are server-side components. It is not rendered to the browser and is inaccessible to JavaScript. It is designed to work with elements that have an href, action or formaction attribute, and it either adds the attribute value to the query string of the generated href, or as a URL segment depending on the route template for the target page.
Generally, you shouldn't pass POST data within the URL, so instead, you can wire up a click event handler to the confirmDeleteButton that initiates an AJAX post that passes the deleteid:
$('#confirmDeleteButton').on('click, function(){
$.post('/yourpage',{deleteid: itemId}, function(){
// process the call back
})
})

Flask add modal to ask before deleting. How to get working?

In my Flask APP i have a page with a link to delete:
Is inside a table each row have this id, here I am sending the ID (that normaly I use to delete):
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" id="submits" onclick="send_to_modal('{{post.id}}')">
Borrar
</button>
Here is my javascript:
function send_to_modal(id){
document.getElementById("exampleModalLabel").innerHTML = id;
};
The modal:
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"> </button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" onclick="modal_a_funccion()">SI</button>
<button type="button" class="btn btn-danger" data-bs-dismiss="modal">NO</button>
</div>
</div>
</div>
</div>
I don´t know how to send the ID to another function that is charged to delete the specified data:
This is my function that works correcty and delete the data giving the ID:
function modal_a_funccion(id){
console.log("Solicitando un report para: "+id);
//fetch('/report/' + olt_hostname).then(function(response) {
fetch('/task/report_celery/' + id).then(function(response) {
response.json().then(function(data) {
for (var x of data.ip) {
console.log("REPORT_fetch recibe (IP): " +x.ip_oob)
console.log("REPORT_fetch recibe (ESTADO): " +x.estado)
};
});
});
};
I would like to know how to to it.
What I intend to do is add a modal to ask the user for confirmation whether or not to delete. I can't find a way to pass the Id to the function that is in charge of doing the deletion. I would like to know how to do it. Thank you so much.
A possible solution (in a different way)
When user clicks on delete for a row, add a class e.g. to_delete. Then display the modal popup asking if user wants to go ahead with the delete or not.
If user says no, close the modal and remove the class again
If user says yes, call the delete function
For 3, you do something like
// Find the element that user has marked for delete
const element = document.querySelect(".to_delete")
const id = element.id;
For 2, you do something like
// Find the element that user has marked for delete and remove the delete mark
document.querySelect(".to_delete").classList.remove("to_delete")

Display entire dictionary in modal from grid-table in Razor view with Jquery

I have a pop-up modal (in a partial) that I need to display the contents of a dictionary in a grid-table. It currently works fine, but only if the dictionary is being returned with one {key, val} pair. I cannot seem to make it work for more than one key/val pairs properly. If there is more than one, it is concatenating them all together in the same cols. I also need the function to remove the previous vals when the modal is re-opened. It does this part fine, but I think the Jquery manipulations to add & remove them may be hindering my attempt to add the values.
To clarify, this works with a returned Dictionary that has one {key, value} pair, but I need for it to work with more than one as well without concatenating them together. For example if returned:
{valName1, val1}
{valName2, val2}
{valName3, val3}
Below is my Modal and the Jquery I am using:
<div class="modal fade" id="paramsModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header modal-header-primary">
<a class="btn btn-xs btn-primary pull-right" data-dismiss="modal" aria-label="Close"><span class="glyphicon glyphicon-remove"></span></a>
<h4 class="modal-title" id="modalTitleText">Job Parameters</h4>
</div>
<div class="modal-body">
<div class="list-group">
<div class="row list-group-item list-group-item-heading container divTableHeading" style="width:inherit; margin-bottom:0px;" id="modalGridHeader">
<div class="col-md-6 font-weight-bold"> Parameter: </div>
<div class="col-md-6 font-weight-bold"> Value: </div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$("button[name='paramsBtn']").click(function () {
/* Grabs ID from col selected */
var $col = $(this).closest('.row').find('.requestId');
var jobRequestId = $col.data('id');
var nameType = $col.data('name');
$.ajax({
url: '#Url.Action("JobPollerParameters", "Tools")',
data: { "jobRequestId": jobRequestId, "name" : nameType},
success: function (results) {
$modal = $('#paramsModal');
$modal.modal("show");
var name = "";
var value = "";
var arr = results;
//loop through arr created from dictionary to grab key(s) and value(s)
for (var key in arr) {
if (arr.hasOwnProperty(key)) {
name += key;
value += results[key];
//Remove previous rows
$("div[name='params']").remove();
//Adding parameters as rows
$('<div class="col-md-6 text-break" name="params"> ' + name + '</div>' + '<div class="col-md-6 text-break" name="params">' + value + '</div>').insertAfter($('#modalGridHeader'));
}
}
}
});
});
</script>
Here is a screenshot of the modal pop-up. In this screen shot, a dictionary with 3 key/val pairs was returned, however you can see that they are all concatenated together.
I was able to achieve what was needed by changing name and value from strings to arrays, and looping through them with another nested for loop:
//loop through arr created from dictionary to grab key(s) and value(s)
for (var key in arr) {
if (arr.hasOwnProperty(key)) {
//name += key;
//value += results[key];
name.push(key);
value.push(results[key])
//Remove previous rows
$("div[name='params']").remove();
for (var i in name) {
//Adding parameters as rows
$('<div class="col-md-6 text-break" name="params"> ' + name[i] + '</div>' + '<div class="col-md-6 text-break" name="params">' + value[i] + '</div>').insertAfter($('#modalGridHeader'));
}
}
}

Dynamic content for model popup based on link selected

I have an array of Accept Reject button. if a user clicks on these buttons separate model popup will show. Accept and reject button link has separate data-id and data-action.
My aim to write a single javascript function to load the content of the model popup instead of repeating the code of modal.
ERB code
<% #non_claim_items.each do |damage_item| %>
<tr>
<td>
<div class="input-prepend">
<span class="add-on"><%= damage_item.estimated_total_repair_cost.currency %></span>
<span class="uneditable-input input-small currency-format"><%= damage_item.estimated_total_repair_cost %></span>
</div>
</td>
<td>
<a data-toggle="modal" data-target="#acceptModel" data-id="<%= damage_item.id %>" data-action = 'accept' class="btn btn-small btn-primary">Accept</a>
<a data-toggle="modal" data-target="#rejectModel" data-id="<%= damage_item.id %>" data-action = 'discuss' class="btn btn-small btn-default">Discuss</a>
</td>
</tr>
<% end %>
<div id="acceptModel" class="modal fade hide" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4><%= t('headings.damage_item.accept_damage') %></h4>
</div>
<div class="modal-body" style="max-height: 500px;">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" ><%= t('navigation.buttons.confirm') %></button>
<button type="button" class="btn btn-default" data-dismiss="modal"><%= t('navigation.buttons.cancel') %></button>
</div>
</div>
</div>
Against each item have one accept/discuss button, data_id and data action are data parameter to model pop.
Script
<script type="text/javascript">
var damage_items = '<%= #non_claim_items.only(:id, :estimated_total_repair_cost, :damage_location_name ).to_json.html_safe %>';
$('a[data-toggle=modal]').click(function () {
if (typeof $(this).data('id') !== 'undefined') {
data_id = $(this).data('id');
action = $(this).data('action');
setModelContent($(this), action, data_id)
}
});
function setModelContent(modal, action, data_id) {
if( action == 'accept')
{
// based on action need to set the body of model pop up
}
}
</script>
I need help to write a javascript function that can set the body of model popup as per action.
Based on data_id, need to pick the corresponding data from the damage_items javascript variable, then data stored in the jquery hash need to show in the model popup body.
You can do it like this:
function setModelContent(modal, action, data_id) {
if (action == 'accept') {
// based on action need to set the body of model pop up
}
// Get damage item by data_id
let damage_item = Object.entries(damage_items).filter(item => item[1].id == data_id);
// Creating dynamically bootstrap elements and setting value of inputs by damage_item
let fisrtLabel = $(document.createElement('label')).text('Cost:');
let fistInput = $(document.createElement('input')).addClass('form-control').val(damage_item[0][1].estimated_total_repair_cost);
let firstCol6 = $(document.createElement('div')).addClass('col-sm-6')
.append(fisrtLabel)
.append(fistInput);
let secondLabel = $(document.createElement('label')).text('location name:');
let secondInput = $(document.createElement('input')).addClass('form-control').val(damage_item[0][1].damage_location_name);
let secondCol6 = $(document.createElement('div')).addClass('col-sm-6')
.append(secondLabel)
.append(secondInput);
let formGroup = $(document.createElement('div'))
.addClass('form-group')
.append(firstCol6)
.append(secondCol6);
// Clearing modal-body and filling it by new elements
$('#acceptModel').find('.modal-body').html("").append(formGroup);
}
Online demo (jsFiddle)

Javascript waiting result of modal

I have a simple question about javascript and bootstrap modal. I have a wizard where I use file upload form, so I check the name of the file and if it doesn't contains some string I have to show a modal where ask if you want to continue anyway. How can I know which button is clicked into modal from javascript or jquery?
I have this code:
if (index==3){
var fileControl = document.getElementById('file');
//Check if the datatable name contains idFLeet and IdCar. REturn -1 if it not contains the string
if (fileControl.files[0].name.indexOf($("#selectedFleet").val()) > -1 && fileControl.files[0].name.indexOf($("#selectedCar").val()) > -1){
//File contains id so you can continue the upload
uploadFunction();
}
else{
$('#warningDatatableModal').modal("show");
//If click on Yes call uploadFunction
//If click on No return false
}
}
HTML modal code:
<div class="modal" id="warningDatatableModal" data-backdrop="static" data-keyboard="false">
<div class="modal modal-warning">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Warning</h4>
</div>
<div class="modal-body">
<p>There is a incongruity between file name and fleet and
car previously selected. Are you sure to continue?</p>
</div>
<div class="modal-footer">
<button id="close" type="button" class="btn btn-outline pull-left"
data-dismiss="modal">Close</button>
<button id="continueButton" type="button" class="btn btn-outline">Continue</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
</div>
After Yeldar Kurmangaliyev advice I have update my code but the wizard go ahed to the next tab instead of waiting into actual tab
if (index==3){
var fileControl = document.getElementById('file');
//Check if the datatable name contains idFLeet and IdCar. REturn -1 if it not contains the string
if (fileControl.files[0].name.indexOf($("#selectedFleet").val()) > -1 && fileControl.files[0].name.indexOf($("#selectedCar").val()) > -1){
//File contains id so you can continue the upload
uploadFunction();
}
else{
$('#warningDatatableModal').modal("show");
$(".modal-footer > button").click(function() {
clicked = $(this).text();
$("#warningDatatableModal").modal('hide');
});
$("#warningDatatableModal").on('hide.bs.modal', function() {
if (clicked === "Cancel"){
return false;
}else {
uploadFunction();
}
});
}
}
If I put this code out of wizard works(it doesn't close modal with cancel button because I use return false that needs for my wizard), but I need to stop wizard waiting modal result.
You can simply attach events to your buttons.
However, the user may want to close the window without action. The design of modal UI and its overlay suggests to click outside the window and close it.
In order to create an event which will fire event always when a user closes your modal, you need to attach to hide.bs.modal event:
$('#warningDatatableModal').on('hide.bs.modal', function() {
});
Here is the working JSFiddle demo.
You can try using the ids of the buttons and attaching a listener to see when they have been clicked like so:
$('#close').on('click',function(){
//do something
});
$('#continueButton').on('click',function(){
//do something
});

Categories

Resources