Ionic: how to programmatically update ion-toggle - javascript

this has been bugging me for ages but I can't figure out how to programmatically change an ion-toggle value.
My toggle starts as on. When someone slides it off, I popup a confirmation. If they cancel the confirmation, I want to reset the toggle back to where it was before:
<ion-toggle ng-model="twitterConnection" ng-change="twitterConnectionChange()">Twitter</ion-toggle>
$ionicPopup.confirm({
title: 'Are you sure?',
template: 'Are you sure you want to disconnect this account?'
}).then(function(res) {
if(res) {
delete $window.localStorage.twitterToken;
delete $rootScope.user.twitterID;
}
else {
$scope.twitterConnection = true;
}
});
I've tried wrapping the $scope.twitterConnection = true; line in $apply, but that gives the "digest already in progress" error. I've tried wrapping it in $timeout, but nothing happens. I'm a relative beginner so all help appreciated, thanks!
EDIT: here's a codepen: http://codepen.io/Shiftlemac/pen/pjZRbP

What I recommend you to do, is the following:
Create the function, which will be responsible for changing the value of the toggle.
So, in your case it will be:
$ionicPopup.confirm({
title: 'Are you sure?',
template: 'Are you sure you want to disconnect this account?'
}).then(function(res) {
if(res) {
delete $window.localStorage.twitterToken;
delete $rootScope.user.twitterID;
$scope.twitterConnectionToggleOn();
}
else {
$scope.twitterConnectionToggleOff();
}
});
and
$scope.twitterConnectionToggleOff = function(){
$scope.twitterConnection = false;
}
$scope.twitterConnectionToggleOn = function(){
$scope.twitterConnection = true;
}

Answer courtesy of the ionic forum:
http://forum.ionicframework.com/t/programmatic-updating-of-ion-toggle-not-working/36155/2?u=shiftlemac
Essentially I needed to use the ng-checked attribute of the ion-toggle and set up the twitterConnection variable as an object as per this kind gentleman's codepen: http://codepen.io/DaDanny/pen/xwJdLr
<ion-toggle ng-model="twitterConnection.checked" ng-change="twitterConnectionChange()" ng-checked="twitterConnection.checked">Twitter</ion-toggle>
$scope.twitterConnection = {
checked: true,
text: 'Twitter' }

first update state on your components like $scope.twitterConnection = true; or $scope.twitterConnection = false ; final run $scope.$apply(); finish
sorry my bad english

Related

How to open/close sidebar in TinyMCE

In the official TinyMCE docs is nothing written about the possibility to manually open/close the sidebar:
https://www.tinymce.com/docs/advanced/creating-a-sidebar/#editorsidebarapi
Can anybody help me? I think it must be something like this:
editor.getSidebar('mysidebar').close();
I need it, because I want to close my custom sidebar in my file browser callback.
Use tinymce.activeEditor.execCommand('togglesidebar', false, 'sidebarname'); to toggle the sidebar. You could place event dispacthers and listeners to know if it is currently opened or closed:
tinymce.PluginManager.add('cheminfo', function (editor, url) {
editor.ui.registry.addSidebar('cheminfo', {
tooltip: 'My sidebar',
icon: 'comment',
onShow: function (api) {
var event = new CustomEvent('tinymce-chem-sidebar', {'detail': true});
window.parent.document.dispatchEvent(event);
},
onHide: function (api) {
var event = new CustomEvent('tinymce-chem-sidebar', {'detail': false});
window.parent.document.dispatchEvent(event);
}
});
});
Then (I am using React):
// detect sidebar state open/close
document.addEventListener('tinymce-chem-sidebar', function (e) {
setOpen(e.detail);
});
PS: Make sure the sidebar's name is lowercase or it won't work
adding to #Kristiyan Tsvetanov's solution, an alternative to using event listeners in determining open/close state of sidebar, the following code can be used:
function is_sidebar_open() {
//class names taken from using inspect on the
//sidebar area of the editor in a browser session
if ($(".tox-sidebar__slider").hasClass("tox-sidebar--sliding-closed")) {
return false;
}
else {
return true;
}
}
function open_sidebar(){
if (is_sidebar_open() == false){
tinymce.activeEditor.execCommand('togglesidebar', false, 'sidebarname');
}
}
function close_sidebar(){
if (is_sidebar_open() == true){
tinymce.activeEditor.execCommand('togglesidebar', false, 'sidebarname');
}
}

AngularJS, AngularConfirm - Update Confirmation Dialog once function is completed

I am trying to figure out how to make the following $ngConfirm box update after a function is completed.
After submit is clicked, the following appears (the cog is spinning):
$scope.inProgress = function(){
$ngConfirm({
theme: 'modern',
icon: "fa fa-cog fa-spin fa-.5x fa-fw",
title: 'File is downloading Please wait.',
content: "",
buttons: {
}
});
};
After this box is displayed, the function doSomething() gets called. Once that function returns, I would like to update the display to the following (the cog stops):
$scope.Complete = function(){
$ngConfirm({
theme: 'modern',
icon: "fa fa-cog fa-.5x fa-fw",
title: 'Spreadsheet Generated!',
content: "File size is {$scope.fileSize}, Do you want to save it?",
buttons: {
'Yes, save my file': {
downloadStuff();
$ngConfirm('Spreadsheet saved to "Downloads" folder.');
},
'No, take me back': {
action: function(){
$ngConfirm('Download has been cancelled.');
}
}
}
});
};
And this is the way I currently have it set up in the submit() function inside my controller:
$scope.submit = function() {
$scope.inProgress();
$scope.doSomething();
$scope.Complete();
};
Using the above code, my application displays both elements layered over eachother. I am stuck trying to figure out how to make $scope.inProgress() update with the details inside $scope.Complete() once $scope.doSomething() returns.
Could someone offer me some advice on what changes I need to make? I've tried to tinker with $scope.inProgress at the end of the submit function, but I always end up displaying a new confirm box or not actually changing something.
My current idea is something along the lines of
$scope.ConfirmationControl = function() {
$scope.inProgress(){
storageService.doSomethingCool().then(
$scope.inProgress() = //updated elements
)
}
}
Does that make sense? Am I close or thinking about this totally wrong?
Thank you in advance for your help! :)
Angular Confirm
There is an example of how to change content on the site. https://craftpip.github.io/angular-confirm/#quickfeatures. Under the Features header you can click on the button labeled "Dialogs" to see an example. Basically you will need to put everything in the content: option with some scope variables. When doSomething() is done, set a $scope variable ($scope.somethingWasDone in this case) and in your dialog have the ng-if. Below is an untested example.
$scope.inProgress = function(){
$scope.title = 'File is downloading. Please wait.';
$ngConfirm({
scope: $scope,
icon: "fa fa-cog fa-spin fa-.5x fa-fw",
content: '<h2>{{title}}</h2>' +
'<div ng-if="somethingWasDone">' +
'<div>File size is 250kb, do you want to save it?</div>' +
'<button ng-click="downloadStuff()">Yes</button>' +
'<button ng-click="cancel()">No</button>' +
'</div>'
});
};
// when your doSomething function is done
$scope.doSomething().then(function(result) {
$scope.title = 'Spreadsheet Generated!';
$scope.somethingWasDone = true;
});

Javascript redirect only seems to work when chrome debugger is open

I have written a Jquery-Ui Dialog to popup as a confirmation on particular links. This however does not redirect to my Delete page correctly. However if I open the debugger in chrome to debug, then the code works as expected.
I have found the same question, however the solution does not seem to work for me. It is exactly the same scenario though. Question here JavaScript redirect not working and works only in Chrome if debugger is turned on
So I have my link
<div id="confirm-dialog">
<div class="dialog-inner">
<p id="confirm-dialog-message"></p>
</div>
</div>
Delete
And I have my javascript
$('.confirmLink').click(function (e) {
BodyScrolling(false);
var theHref = $(this).attr("href");
var theTitle = $(this).attr("title") == null ? "Confirm..." : $(this).attr("title");
var theText = $(this).attr("data-confirm-message") == null ? "Are you sure?" : $(this).attr("data-confirm-message");
$("#confirm-dialog-message").html(theText);
$("#confirm-dialog").parent().css({ position: "fixed" }).end().dialog("open");
$("#confirm-dialog").dialog({
title: theTitle,
close: function() {
BodyScrolling(true);
},
buttons: [
{
text: "Yes",
class: "mws-button red",
click: function () {
$("#confirm-dialog").dialog("close");
window.location.href = theHref;
return false;
}
},
{
text: "No",
class: "mws-button black",
click: function () {
$("#confirm-dialog").dialog("close");
}
}]
});
return false;
});
So when I click my Delete link, I am indeed presented with my confirm dialog with Yes and No buttons, css styled correctly, and has captured the link href and bound it to the Yes button. If I click "No", I am kicked back and nothing further happens - Correct!
If I click Yes, it should take send me on to the original href that it captured. I have thrown alert(theHref) on the Yes Button click just before the redirect and it does show me the correct address (/Customer/Delete/73865878346587), but the redirect does not happen.
When I open the chrome debugger to debug the javascript or see if any errors occurred, then everything works as expected and redirects me correctly!
In IE, it does not work either.
I have tried...
window.location.href = theHref
window.location = theHref
location.href = theHref
$(location).attr('href', theHref)
I have also tried adding return false; after my redirect. Nothing works.
The link I added above to the same question said to make sure that the Yes button is being rendered on the page as a ... which mine is.
Can anyone shed any light?
Instead of window.location.href = theHref;
have you tried window.location.replace(theHref);?
Back to basics, try: window.location = theHref;
Well I have found the answer. Javascript was a red herring!
I did try to remove the confirmLink jQuery class so that the link was just a standard link that went straight to my controller to perofm my delete. When I did this test, the link worked perfectly. Therefore I denoted the problem be with my javascript. However, it seems that this was not quite the case and had only worked again if the Debugger in Chrome had been or was open at the time aswell.
When I revisited the non confirm link option again, I found this not to work properly, therefore denoting the problem not with the javascript.
It appears that you cannot perform a Delete action from a HTML Link in MVC. This is obviously because of security risks involved as anyone could perform a Delete on an Id. I had thought of this in my implementation and had added code to check where the Request had come from and if it wasn't from my List page, then it threw back an error and wouldn't perform the Delete. It didn't matter what I named my controller either, eg Test, the link performing my HTTP GET request would never hit this. There must be some algorithm that determines what the action is doing and stops you from performing the action on a HttpGet request. For more information about Delete Actions, check out this post http://stephenwalther.com/archive/2009/01/21/asp-net-mvc-tip-46-ndash-donrsquot-use-delete-links-because
It seems that you can only perform this by a HTTP Post, which means either using a Ajax.ActionLink or by using a Form and a submit button. Then your Action must be specified for HttpPost.
If, like me, you wish to keep your Link as a HTML Link, then you can do the following which is what I did, code below. I kept my HTML Link, set it up to point to my HttpPost Delete Action. Added my confirmLink class for jquery to bind my dialog box to. I pick up the link href and set the Yes button in the jquery dialog to dynamically create a Form and set the method to post and the action to the links href. Then I can call submit on the new dynamically created form to perform my Post to my Delete action.
My Delete Link
Html.ActionLink("Delete", "Delete", "Caterer", new { id = caterer.Id }, new { #class = "mws-ic-16 ic-delete imageButton confirmLink", #data_confirm_title = "Delete " + caterer.Name, #data_confirm_message = "Are you sure you want to delete this caterer, " + caterer.Name + "?" })
My Javascript
function LoadConfirm() {
$('.confirmLink').click(function (e) {
e.preventDefault();
BodyScrolling(false);
var actionHref = $(this).attr("href");
var confirmTitle = $(this).attr("data-confirm-title");
confirmTitle = confirmTitle == null ? "Confirm..." : confirmTitle;
var confirmMessage = $(this).attr("data-confirm-message");
confirmMessage = confirmMessage == null ? "Are you sure?" : confirmMessage;
$("#confirm-dialog").dialog({
autoOpen: false,
modal: true,
width: 400,
closeOnEscape: true,
close: function () { BodyScrolling(true); },
title: confirmTitle,
resizable: false,
buttons: [
{
text: "Yes",
class: "mws-button red",
click: function () {
StartLoading();
$(this).dialog("close");
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", actionHref);
form.submit();
}
},
{
text: "No",
class: "mws-button black",
click: function () {
$("#confirm-dialog").dialog("close");
return false;
}
}
]
});
$("#confirm-dialog #confirm-dialog-message").html(confirmMessage);
$("#confirm-dialog").parent().css({ position: "fixed" });
$("#confirm-dialog").dialog("open");
});
}
My Action
[HttpPost]
[Authorize(Roles = "User")]
public ActionResult Delete(long id)
{
//Perform my delete
return RedirectToActionPermanent("List");
}

Calling href in Callback function

I have a anchor tag in my page for logout.
<a href="/logout/" id="lnk-log-out" />
Here I am showing a Popup for confirmation with jQuery UI dialog.
If user click Yes from dialog it has to execute the link button's default action, I mean href="/logout".
If No clicked a Popup box should be disappeared.
jQuery Code
$('#lnk-log-out').click(function (event) {
event.preventDefault();
var logOffDialog = $('#user-info-msg-dialog');
logOffDialog.html("Are you sure, do you want to Logout?");
logOffDialog.dialog({
title: "Confirm Logout",
height: 150,
width: 500,
bgiframe: true,
modal: true,
buttons: {
'Yes': function () {
$(this).dialog('close');
return true;
},
'No': function () {
$(this).dialog('close');
return false;
}
}
});
});
});
The problem is I am not able to fire anchor's href when User click YES.
How can we do this?
Edit: Right now I managed in this way
'Yes': function () {
$(this).dialog('close');
window.location.href = $('#lnk-log-out').attr("href");
}
In the anonymous function called when 'Yes' is fired, you want to do the following instead of just returning true:
Grab the href (you can get this easily using $('selector').attr('href');)
Perform your window.location.href to the url you grabbed in point 1
If you want the a tag to just do it's stuff, remove any preventDefault() or stopPropagation(). Here I have provided two different ways :)
Don't use document.location, use window.location.href instead. You can see why here.
Your code in the 'Yes' call should look something like, with your code inserted of course:
'Yes': function () {
// Get url
var href = $('#lnk-log-out').attr('href');
// Go to url
window.location.href = href;
return true; // Not needed
}, ...
Note: Thanks to Anthony in the comments below: use window.location.href = ... instead of window.location.href(), because it's not a function!
I have used this in many of my projects so i suggest window.location.href
'Yes': function () {
$(this).dialog('close');
window.location.href="your url"
return true;
},

How to achieve a return confirm like dialog but using jgrowl?

I am working with a forum script (simple machines forum)
It is using this kind of javascript confirmation messages:
Remove
And I want to use jgrowl instead that... something like:
<a href="http://domain.net/index.php?action=deletemsg;topic=1.0;msg=1;c6c7a67=f9e1fd867513be56e5aaaf710d5f29f7" onclick="$.jGrowl('Remove this message?', { header: 'Confirmation', sticky: true });"/>Remove</a>
But... how to achieve true/false javascript return using jgrowl?
Can be this done in just one line?
Best regards!
luciano
edited to support using the href
you can't do it just like that because jGrowl will not be modal and block your page's behaviour.
However you could create a function for the code you want to execute after the choice was done, and then call it from within the notification
check this example http://jsfiddle.net/rcxVG/11/
html
<body>
link for 1<br>
link for 2<br>
Will we notify again<div id="will-notitfy-again">yes</div>
<br>
now... If you want to return then
click me
</body>
js
function startDemo(id)
{
$.jGrowl("to do not notify again click <a href='javascript:notFor("+id+")' onclick='closeNotif(this);'>here</a>!", { sticky: true });
}
function notFor(id){
alert("not anymore for "+id);
$("#will-notitfy-again").html("remember, notFor was hit for"+id);
}
function closeNotif(panel){
$(".jGrowl-notification").has(panel).find(".jGrowl-close").click();
}
var counter=0;
var confirmedAttr="data-confirmed";
function returnModal(field){
var $field=$(field);
if($field.attr(confirmedAttr)=="true"){
location.href=$field.attr("href");
}else{
counter++;
//save the element somewhere so we can use it (don't know if it has an unique-id)
$(document).data("id"+counter,$field);
$.jGrowl("click <a href='javascript:confirmClick("+counter+")' onclick='closeNotif(this);'>here</a> to go to google!", { sticky: true });
return false;
}
}
function confirmClick(variableId){
var $field=$(document).data("id"+variableId);
$field.attr(confirmedAttr,"true");
$field.click();
}
Let me know if this was good enought

Categories