No update $scope in view after function - javascript

I have an array in my controller called this.selectedCourses. This array have some items which are showed in my view as a list.
After some steps I have this:
this.checkAddedCourses = function(studentCourses){
...
if(repeatedCourses.length != 0){
sweetAlert({
title: title,
text: text + ' ' + courseList,
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: confirmButtonText,
closeOnConfirm: false,
html: true
},
function(){
angular.forEach(repeatedCourses, function(repeatedCourse){
this.removeCoursePurchase(repeatedCourse);
}.bind(this));
swal("Deleted!", "Your purchase has been refreshed.", "success");
}.bind(this));
}
}
When the user click on button 'Remove' the items are removed fine from the array, I've already checked, but in my view I still seeing those items until I do something with that array. Is like it isn't refreshing the array after remove the elements.
Thanks.
PD: sweetAlert is a library for alerts.

Use $scope instead of this for data-binding on your view - so $scope.selectedCourses. Remember to pass $scope into your controller as a dependency.

Ok I've solved with the ´$apply´ function using it like this:
sweetAlert({
title: title,
text: text + ' ' + courseList,
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: confirmButtonText,
closeOnConfirm: false,
html: true
},
function(){
angular.forEach(repeatedCourses, function(repeatedCourse){
$rootScope.$apply(function() {
this.removeCoursePurchase(repeatedCourse);
}.bind(this));
}.bind(this));
swal("Deleted!", "Your purchase has been refreshed.", "success");
}.bind(this));

Related

SweetAlert2 form validation does not return

Trying to use SweetAlert2 with a form sending confirmation. But no matter what I try, I can't get it to work.
Swal.fire({
title: err_msg,
//html: strCEmail,
text: 'hello',
type: 'question',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, send it!'
}).then((result) => {
if (result.value) {
// xxxxxxxxxxxxxxxxxxxx
}
});
The code reachs the xxxxxxxxxxxxx fine, but whatever I put there doesn't trigger the form to submit.
I've tried the obvious
return true;
But that didn't work. Then after some digging I found a suggestion to submit the form like this:
document.forms["myform"].submit();
or
form.submit();
Which didn't work.
So... what can I use to submit the form once the user has selected submit in SweetAlert2?
Most likely you're trying to access something that doesn't exist.
Based on SWAL documentation and this post: Response from Sweet-alert confirm dialog
you should just try to do "if(result)" instead of "if(result.value)".
Also, as I commented above, you should go through the documentation and read the pokémon example, it may give you a hint: sweetalert.js.org/guides/#advanced-examples
Give id to your form
<form action="your-action" method="post" id="my_form">
In js:
Swal.fire({
title: err_msg,
text: 'hello',
type: 'question',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, send it!'
}).then((result) => {
if (result.value) {
$(document).find('#my_form').submit();
}
});

Prevent Page navigation - SweetAlert

I'm trying to replace the JS box dialog with sweet alert dialog box.
At normal cases, it works perfectly.
But, at the time of navigating the page on confirmation. It didn't work.
JS box :
var confirm = window.confirm("Warning! You may have unsaved data,it will be lost..!" + "\n" + "Are you sure want to leave this page ?");
if (confirm) {
$scope.$eval(event); //It prevents the page to nav ,until i confirm it.
} else {
event.preventDefault();
}
It works.
In case of sweetalert, I'm using the same scenario
$scope.validation = function(event) {
//....
sweetAlert({
title: "Are you sure?", //Bold text
text: "Your will not be able to recover this imaginary file!", //light text
type: "warning", //type -- adds appropiriate icon
showCancelButton: true, // displays cancel btton
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
//Function that triggers on user action.
if (isConfirm) {
$scope.$eval(event); //????
/* sweetAlert(
'Deleted!',
'Your file has been deleted.',
'success'
)*/
} else {
event.preventDefault();
}
}
For state change ,
.state('ModuleName',{
url : '/ModuleName',
templateUrl : 'ModuleMenu/ModuleName.html',
controller : 'modulectrl',
resolve : {
loadPlugin : function($ocLazyLoad) {
return $ocLazyLoad
.load([
{
name : 'css',
insertBefore : '#app-level',
files : [
'../static/vendors/bower_components/nouislider/jquery.nouislider.css',
]
},
{
name : 'vendors',
files : [
'../static/vendors/bower_components/angular-farbtastic/angular-farbtastic.js' ]
},
{
name : 'ComliveApp',
files : [ '../static/scripts/controller/modulectrl.js' ]
} ])
}
}
})
On href,the respective view is loaded. My point is that page should not be loaded until sweetAlert confirms it.
Suggestions/answers are appreciated.
Thanks.

Repetitive javascript cycle

good night, I have this view (the image) which is part of an invoice, this is precisely the detail of the invoice, and I have in this detail a javascript function so that while I write the name of the product I look for the product in the database and when I select it I fill the input of the unit price corresponding to that product, until there all wonders, but the problem is that by pressing the + button to enter a new line and load a new product the function javascript no longer works, it occurred to me that I can use a foreach or something similar to make that function work every time a new line is inserted but I can not make it work, I leave the code:
//search in the database
$("#inputPrecioProducto").devbridgeAutocomplete({
showNoSuggestionNotice: true,
serviceUrl: '/maderas/facturar/leer_productos',
noSuggestionNotice: 'No se encontraron datos',
onSelect: function (suggestion) {
$('#inputIdProducto').val(suggestion.data)
$('#inputPrecioUnidad').val(suggestion.precio_unidad);
}
});}
// Product Field Repeater
$('.repeater').repeater({
hide: function (deleteElement) {
var elemento=$(this);
swal({
title: "Estas Seguro?",
text: "Se borrará toda la fila!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Si, bórralo!",
cancelButtonText: 'Cancelar',
closeOnConfirm: false
}, function(){
swal("Producto Borrado!", "Se ha eliminado el Producto.", "success");
elemento.remove();
sumarTotales();
crearIgv();
});
},
isFirstItemUndeletable: true
});
// ./ Product Field Repeater

Wait on SweetAlert response

I currently have a function that asks the user for confirmation when changing a value in a dropdown. This works fine using the standard JavaScript confirm(). Here's the fiddle.
var prev_val;
$('#dropdownId').focus(function () {
prev_val = $(this).val();
}).change(function () {
$(this).blur();
var success = confirm('Are you sure you want to change the Dropdown?');
if (success) {
// Proceed as normal.
} else {
// Reset the value & stop normal event
$(this).val(prev_val);
return false;
}
});
But when using SweetAlert, the change event always takes place before I'm able to confirm/cancel. Meaning, when I select a new value, and pressing "cancel", it does not stop the event and reset the previous value. Which it does with the regular JavaScript confirm dialog.
var prev_val;
$('#' + dropdownId).focus(function () {
prev_val = $(this).val();
}).change(function (e) {
$(this).blur();
return swal({
title: "Are you sure?",
text: "Do you want to change the dropdown?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
cancelButtonText: "No",
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
e.preventDefault();
return true;
} else {
$(this).val(prev_val);
return false;
}
});
});
It might also be interesting to note that this JavaScript might even be invalid (pretty new to JavaScript), e.g. returning from the confirm function and from the swal function not functioning.
However, after Googling around, I found people with similar issues.
how-to-use-confirm-using-sweet-alert
how-to-run-a-sweetalert-instead-of-default-javascript-confirm-method
But that seems a bit hacky since it's preventing any action, but when selecting confirm he re-creates the function that should have been called by default. Which seems like quite a hack for something so simple.
Any possibility of the SweetAlert just acting like a regular confirm dialog?
The value does not get set back because this in swal is not the select, but the sweet alert dialog. So in your change event you have to define a variable that holds the changed select element and use it to set the value back when the user clicks 'No'.
.change(function(e) {
var select = this; // save select element to variable
$(this).blur();
return swal({
title: "Are you sure?",
text: "Do you want to change the dropdown?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
cancelButtonText: "No",
closeOnConfirm: true,
closeOnCancel: true
},
function(isConfirm) {
if (isConfirm) {
e.preventDefault();
return true;
} else {
$(select).val(prev_val); // use select reference to reset value
return false;
}
});
});
You can find a working example in this fiddle.
var prev_val;
$('#' + dropdownId).focus(function() {
prev_val = $(this).val();
}).change(function(e) {
$(this).blur();
var self = this;
return swal({
title: "Are you sure?",
text: "Do you want to change the dropdown?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
cancelButtonText: "No",
closeOnConfirm: true,
closeOnCancel: true
},
function(isConfirm) {
if (isConfirm) {
// preventDefault is useless since change event has already happened
// if Confirm is true then do nothing else
// change with prev val
//e.preventDefault();
return true;
} else {
// this here does not refer the dom element
// it might be changed because it is called through the swal library code at a later time, use self which is declared out of the callback context.
$(self).val(prev_val);
return false;
}
});
});

passing variable from data-attribute to onclick function

I have a page with table of a number of records in it
Each row has button on it I want to add an onclick event so it fires a popup message, if they ok it the page diverts to another page passing the value found in the data attribute but I cant get it to work
Jquery looks like this:
var aFeatures = document.querySelectorAll(".sweet-roll");
for (var i = 0; i < aFeatures.length; i++) {
aFeatures[i].onclick = function() {
swal({
title: "Rollback To Selected Version?",
text: "Are you sure you want to rollback to the selected version?",
type: "warning",
showCancelButton: true,
confirmButtonClass: 'btn-danger',
confirmButtonText: 'Yes, Rollback',
closeOnConfirm: false,
//closeOnCancel: false
},
function(){
window.location.href="/cms/rollback.aspx?id="+$(this).data('uuid');
});
};
}
};
So that every button with the class 'sweet-roll' gets the onclick event.
Each html row looks like this:
<a class="btn btn-app sweet-roll" data-uuid="97aaa88c-ac9f-11e4-807b-0026b9ba6b95"><i class="fa fa-reply-all"></i>Rollback</a>
But it keeps saying the value is undefined as if it cant find the data-uuid value?
Your this is referencing SweetAlert caller, but not your element. What you need to do is to save it in some variable, let's say _this
var aFeatures = document.querySelectorAll(".sweet-roll");
for (var i = 0; i < aFeatures.length; i++) {
aFeatures[i].onclick = function() {
var _this = this
swal({
title: "Rollback To Selected Version?",
text: "Are you sure you want to rollback to the selected version?",
type: "warning",
showCancelButton: true,
confirmButtonClass: 'btn-danger',
confirmButtonText: 'Yes, Rollback',
closeOnConfirm: false,
//closeOnCancel: false
},
function(){
window.location.href="/cms/rollback.aspx?id="+$(_this).data('uuid');
});
};
}
};

Categories