Set flash message after redirect in angularjs - javascript

I am just starting with Angular js. I have a doubt in that. I want to set flash messsage after redirect.
In my case, I have a form and am saving the data through http requst. In the success function I put window.location(). It is another page. I want to set a flash message in that page.
js
$scope.Save_Details = function (id)
{
$http.post(base_url+"sur/sur/save_data/"+id,{data:$scope.Surdata}).
success(function(response) {
// $scope.successTextAlert = "Saved";
// $scope.showSuccessAlert = true;
window.location = "#/surpage/nextpage?show_message= true";
});
}
new update
var messageFlag = $location.search().show_message;
if(messageFlag && messageFlag === 'true'){
alert(messageFlag);
$scope.successTextAlert = "Saved";
$scope.showSuccessAlertMsg = true;
}
view
<div class="alert alert-success" ng-show="showSuccessAlert">
<button type="button" class="close" data-ng-click="switchBool('showSuccessAlert')">×</button> <strong> {{successTextAlert}}</strong>
</div>
Anyone help me?

Put this code in HTML -
<!-- message text -->
<div class=" panel-{{alerts.class}}" ng-show="alerts.messages" >
<div ng-repeat="alert in alerts.messages track by $index" class="panel-body alert-{{alerts.class}}" >{{alert}}</div>
</div>
Put this code in angular model -
$rootScope.alert = function(type,msg){
$rootScope.message.push(msg);
$rootScope.alerts = {
class: type,
messages:$rootScope.message
}
}
For success message -
$rootScope.alert('success',"Success !!!");
For Error message -
$rootScope.alert('danger',"Error.");

You can use toastr JS specially for flash.
http://codeseven.github.io/toastr/demo.html
By using below js code, you can display a flash message.
For success message :
toastr"success";
For Error message :
toastr"success";

EDIT - Adding code
yourAppModule.controller('nextPageController', function($location){
var messageFlag = $location.search().show_message;
if(messageFlag && messageFlag === 'true'){
//show your message
}
});
When you navigate to "nextpage" pass a flag along -> #/surpage/nextpage?show_message= true
In the "nextpage" controller, read the query string value for
"show_message" ( inject $location to your controller and get value
using $location.search().show_message)
if that value == true, show your flash message

Related

Trying to convert a javascript button to a lightning component

I cannot convert a java button using the converter
I tried to use the Lightning Experience Configuration Converter to convert a java button to a lightning Component (Full) yet everytime (I am live in Production), i get this error "We were unable to deploy some metadata to your org due a timeout" Since i can preview the component and the controller code I believe i can simply copy that to a sandbox and then push.
I am getting errors when creating the component (copied the code-Developer Console-New Lightning component) and I got other errors when creating the Controller - New-Apex Class..
I have inserted a images of the code supplied by the converter and the original (the component, the controller and the original)
It was meant to assign a unique order number to an inscription on click.
The controller
({
apexExecute : function(component, event, helper) {
//Call Your Apex Controller Method.
var action = component.get("c.updateOrderNumber");
action.setParams({
'inscriptionId': ''+component.get('v.sObjectInfo.Id')+''
});
action.setCallback(this, function(response) {
var state = response.getState();
console.log(state);
if (state === "SUCCESS") {
//after code
if (''+component.get('v.sObjectInfo.Order_Number__c')+'' == '') { var result = response.getReturnValue();
window.location.reload(false);
} else helper.showTextAlert(component, 'Order Number already Exist');
} else {
}
});
$A.enqueueAction(action);
},
accept : function(component, event, helper) {
$A.get("e.force:closeQuickAction").fire();
}
})
The Component
<aura:component controller="UpdateOrderNumberOnButtonClick" extends="c:LCC_GenericLightningComponent" >
<aura:handler event="c:LCC_GenericApplicationEvent" action="{!c.apexExecute}"/>
<aura:set attribute="partially" value="false"></aura:set>
<aura:attribute name="showAlert" type="Boolean" default="false"/>
<aura:attribute name="alertText" type="String"/>
<aura:set attribute="isAdditionalObject" value="false"></aura:set>
<div>
<div class="slds-scrollable slds-p-around_medium slds-text-heading_small" id="modal-content-id-1">
<aura:if isTrue="{!v.showAlert}">
<p class="slds-hyphenate">{!v.alertText}</p>
<aura:set attribute="else">
<div style="height: 6.75rem;">
<div role="status" class="slds-spinner slds-spinner_large slds-spinner_brand">
<span class="slds-assistive-text">Loading</span>
<div class="slds-spinner__dot-a"></div>
<div class="slds-spinner__dot-b"></div>
</div>
</div>
</aura:set>
</aura:if>
<br/>
</div>
<footer class="slds-modal__footer">
<lightning:button class="slds-button_brand" onclick="{!c.accept}" label="Accept"/>
</footer>
</div>
</aura:component>
The original Javascript button
Here's your current JavaScript button code, to compare with our suggestion.
{!REQUIRESCRIPT("/soap/ajax/24.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/20.0/apex.js")}
var orderNumber = '{!Inscription__c.Order_Number__c}';
if(orderNumber == ''){
var result= sforce.apex.execute("UpdateOrderNumberOnButtonClick", "updateOrderNumber", {inscriptionId:'{!Inscription__c.Id}'});
window.location.reload(false);
}
else
alert('Order Number already Exist');

pdf directive not showing pdf file in Angular JS

I need to open a PDF in Angular, I have tried using pdf.js and pdf.combined.js directives but unable to display the data. My Angular ver - 1.4.8
Since it shouldn't have downloadable button or PDF URL visible.So i can't use google docs viewer or directly opening it as BLOB Object.
Can someone help me in solving this, sorry bit lengthy but any help is appreciated,Thanks !!
Code -
1) First controller which has method to open a modal window on click -
vm.getCallRates = function() {
ModalService.showModal({
templateUrl: absoluteURL('app/profile/tariff.html'),
inputs: {},
controller: 'tariffController'
});
}
2) tariff.html has a div with ng-pdf and controller like this -
<div ng-controller="tariffController">
<ng-pdf template-url="app/profile/pdfViewer.html" canvasid="pdf-canvas"
scale="1.5" ></ng-pdf>
</div>
3) tariffController -
(function () {
'use strict';
angular
.module('app.profile')
.controller('tariffController', tariffController);
tariffController.$inject = ['$scope'];
function tariffController($scope) {
$scope.pdfUrl = "http://172.16.23.26:3123/images/Invoice.pdf";
//$scope.pdfName = 'Relativity: The Special and General Theory by Albert Einstein';
//$scope.pdfPassword = 'test';
$scope.scroll = 0;
$scope.loading = 'loading';
$scope.getNavStyle = function(scroll) {
if(scroll > 100) return 'pdf-controls fixed';
else return 'pdf-controls';
}
$scope.onError = function(error) {
console.log(error);
}
$scope.onLoad = function() {
$scope.loading = '';
}
$scope.onProgress = function (progressData) {
console.log(progressData);
};
$scope.onPassword = function (updatePasswordFn, passwordResponse) {
if (passwordResponse === PDFJS.PasswordResponses.NEED_PASSWORD) {
updatePasswordFn($scope.pdfPassword);
} else if (passwordResponse === PDFJS.PasswordResponses.INCORRECT_PASSWORD) {
console.log('Incorrect password')
}
};
}
}());
4) pdfViewer.html -
<nav ng-class="getNavStyle(scroll)">
<button ng-click="goPrevious()"><span><</span></button>
<button ng-click="goNext()"><span>></span></button>
<button ng-click="zoomIn()"><span>+</span></button>
<button ng-click="fit()"><span>100%</span></button>
<button ng-click="zoomOut()"><span>-</span></button>
<button ng-click="rotate()"><span>90</span></button>
<span>Page: </span>
<input type="text" min=1 ng-model="pageNum">
<span> / {{pageCount}}</span>
<span>Document URL: </span>
<input type="text" ng-model="pdfUrl">
</nav>
<hr>
{{loading}}
<canvas id="pdf-canvas"></canvas>
Attaching snapshot for response of PDF data load -
Also "pdf" dependency error comes on browser refresh but not on first loading -
My problem was with div. I had not included CSS class for Popup / Modal Window. So overlay window was not showing although data was getting loaded as shown in above logs.
The dependency error got resolved when i added PDF to my app.modules.js base class dependency,hence accessible through out app.
You need to include angular-pdf.js in your HTML, this allows you to use the ng-pdf directive.
You need also to include the directive as a dependency when defining the angular app:
var app = angular.module('app.profile', ['pdf']);
You can see an example of "getting started" at this link: https://github.com/sayanee/angularjs-pdf#getting-started

Bootstrap modal won't close on click

I am very new to web dev. Still not too familiar with JavaScript. I am making an error message using that will load using code one of our dev guys created for a different page. I created modals that show on a click event and then close on a click event. For this one I am having the modal show based on returned URL parameters. And I am using code I copied from another page one of our dev guys made (not with Bootstrap modals).
The code below makes the modal show, but the buttons used to close the modal don't work. Not sure why.
This is the tag that will append the URL when returned:
(**...?companyName=ACME47 & err1=0 & err2=0 & err3=1**)
When the error values are 1 is loads the page to show the error modal with the text for that error in it.
Here is the code I'm using for the form (not attaching the style sheet, so it looks different).
jQuery(document).ready(function() {
// jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results == null) {
return null;
} else {
return results[1] || 0;
}
}
// Get url parameters
var err1 = new Number($.urlParam('err1'));
if (isNaN(err1)) {
err1 = new Number(0);
}
var err2 = new Number($.urlParam('err2'));
if (isNaN(err2)) {
err2 = new Number(0);
}
var err3 = new Number($.urlParam('err3'));
if (isNaN(err3)) {
err3 = new Number(0);
}
console.log('err1: ' + err1); // Writes a message to the browser console [f12]
console.log('err2: ' + err2); // Writes a message to the browser console [f12]
console.log('err3: ' + err3); // Writes a message to the browser console [f12]
console.log('CompanyName: ' + $.urlParam('companyName')); // Writes a message to the browser console [f12]
// Display error message function
// Read a page's GET URL variables and return them as an associative array.
if (err1 > 0) {
$("#error-box").show();
$("#error-1").show();
};
if (err2 > 0) {
$("#error-box").show();
$("#error-2").show();
};
if (err3 > 0) {
$("#error-box").show();
$("#error-3").show();
};
});
<div class="modal" id="error-box" style="display: none;" tabindex="-1" role="dialog" aria-labelledby="error-boxLabel">
<div class="modal-dialog" role="document" style="height:200px;">
<div class="modal-content" style="height: 100%;">
<div class="modal-header alert-danger">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title text-danger">Form Submission Error</h4>
</div>
<div class="modal-body alert-danger" style="height: 100%;">
<div class="textWrapper">
<ul>
<li id="error-1" style="display: none;">That email address is already in use. (01)</li>
<li id="error-2" style="display: none;">A company with that name already has an account in this system. (02)</li>
<li id="error-3" style="display: none;">An unknown error has occurred. If your E-Mail or Phone Number was correctly filled in, you will be contacted shortly. (03)</li>
</ul>
</div>
</div>
<div class="modal-footer modal-footer-text">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
You shouldn't be using jQuery's show() method to show the modal. Doing so doesn't register it with Bootstrap, so there's nothing to close with elements possessing the data-dismiss attribute. Use Bootstrap's method:
$("#error-box").modal('show');
Note that you may also need to use Bootstrap's show.bs.modal callback to show your error containers. It's possible that they won't be available to jQuery until the modal is initiated.
This is what I think you want see fiddle https://jsfiddle.net/sxh0n7d1/53/
Note: I set all the errors to visible in the fiddle, so that there is something to see how it works.
add this to your javascript
$('.close, .btn-danger').click(function() {
$( "#error-box" ).hide();
});

Show callback after button click

This is pretty a newby question but I can't figure this one out because it is a different approach/way of writing then I'm used to!
I'm using the app "Back in Stock" for a webshop that's not shopify but something like that. This app shows a modal when a product is out of stock to register your email to recieve an update.
Further I created my own modal because of translation issues and more country related stuff.
I'm having trouble to create or to run a function to show a success or error message when I click a button.
The docs say that this is the way to grab all messages:
var notificationCallback = function(data) {
var msg = '';
if (data.status == 'OK') {
msg = data.message; // just show the success message
} else { // it was an error
for (var k in data.errors) { // collect all the error messages into a string
msg += data.errors[k].join();
}
}
alert(msg);
}
I have created a function that shows the popup and handles the submit:
<button class="notify_button pp pull-right" data-product-id="{{ product.id }}" data-variant-id="{{ product.vid }}" onclick="notify_me_function(this,event);">{{ 'Email when available' | t }}</button>
function notify_me_function(el ,event){
var variantId = $(el).data('variant-id');
var productId = $(el).data('product-id');
var itemName = $(el).closest('.item').find('.item-name').text();
$('#notify__').modal('show');
$('#notify__ #notify_button').on('click', function(e) {
e.preventDefault();
var email = $('#notify__ .form-horizontal input').val();
var $container = $('.completed_message');
// this piece of code below is also from the docs /////////
BIS.create(email, variantId, productId).then(notificationCallback);
//something like this?? ///
$container.txt(msg);
});
}
How do I show the msg from notificationCallback everytime I click the submit button inside the modal?
In your notify modal dialog html markup put something like
<div id="#puttexthere"></div>
then you can do
$('#puttexthere').text(msg);
Hopefully what you need.

jQuery plugin using only last element's values

I built a plugin that's supposed to transform any button into a modal style form, given a url where the form can be fetched.
It works fine with only one element, but when the selector returns multiple elements, all buttons use the last element's data when the get & post methods are called inside the plugin.
I've tried several answered question in SO, but haven't been able to locate and fix the bug. Looks like I'm missing something.
Here's the complete code. You'll see some {% django tags %} and {{ django context variables }} but just ignore them.
Thanks!
A.
EDIT: typo; EDIT2: added html; EDIT3: removed django tags and context vars.
<div class="modal fade" id="modal-1234" data-uuid="1234">
<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" id="title-1234">Title</h4>
</div>
<div class="modal-body" id="body-1234">Body</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" id="cancel-1234">Close</button>
<button type="button" class="btn btn-primary" id="confirm-1234">Save changes</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
(function($){
// define the modalform class
function ModalForm($button){
/*
You can use ModalForm to automate the ajax-form-modal process with TB3.
Usage:
var mf = new ModaForm($('#my-button')); // that's it
*/
self = this;
self.$button = $button;
self.$modal = $('#modal-1234');
// get vars
self.target = self.$button.attr('data-target');
self.uuid = self.$modal.attr('data-uuid');
self.$modal_title = $('#title-' + self.uuid);
self.$modal_body = $('#body-' + self.uuid);
self.$modal_confirm = $('#confirm-' + self.uuid);
self.modal_confirm_original_text = self.$modal_confirm.html()
self.$modal_cancel = $('#cancel-' + self.uuid);
self.$alerts = $('[data-exsutils=push-alerts]').first();
self.$spinner = $('<p class="center"><i class="ace-icon fa fa-spinner fa-spin orange bigger-300"></i></p>');
// bind button click to _get
self.$button.on('click', function(e){
e.preventDefault();
self._get();
});
}
ModalForm.prototype._get = function(){
/*
Issue a get request to fetch form and either render form or push alert when complete.
*/
var self = this;
// show modal, push spinner and change title
self.$modal.modal('show');
self.$modal_body.html(self.$spinner);
self.title = typeof(
self.$button.attr('data-title')) !== 'undefined' ?
self.$button.attr('data-title') : 'Modal form';
self.$modal_title.html(self.title);
// get content
$.ajax({
type: 'GET',
url: self.target,
statusCode: {
403: function(data){
// close modal
// forbidden => close modal & push alert
setTimeout(function(){
self.$modal.modal('hide');
self.$alerts.html(data.responseText);
}, 500);
},
200: function(data){
// success => push form
// note that we will assign self.$form
var $response = $(data);
self.$form = $response.filter('form').first();
self.$modal_body.html($response);
self.$modal_confirm.click(function(e){
e.preventDefault();
self._submit(self.$form);
});
}
},
error: function(data){
console.log(data);
}
});
}
ModalForm.prototype._submit = function(){
/*
Post this.$form data and rerender form or push alert when complete.
*/
var self = this;
// change submit button to loading state
self.$modal_confirm.addClass('disabled').html('Loading...');
// issue pot request
// cleanup
// rebind if rerender or push alerts
$.ajax({
type: 'POST',
url: self.$form.attr('action'),
data: self.$form.serialize(),
statusCode: {
200: function(data){
// this is a form error
// so we must rerender and rebind form
// else we need to rerender and rebind
self.$form.remove();
var $response = $(data);
self.$form = $response.filter('form').first();
self.$modal_body.html($response);
self.$modal_confirm.on('click', function(e){
e.preventDefault();
self._submit(self.$form);
});
},
201: function(data){
// this means object was created
// so we must push an alert and clean up
self.$form.remove();
delete self.$form;
self.$modal.modal('hide');
self.$modal_body.html('');
// we will push alerts only if there is no 201 callback
var callback_201 = self.$button.attr('data-callback-201');
if (typeof(window[callback_201]) !== 'undefined') {
window[callback_201](data);
} else {
self.$alerts.prepend(data);
};
},
403: function(data){
// this means request was forbidden => clean up and push alert
self.$form.remove();
delete self.$form;
self.$modal.modal('hide');
self.$modal_body.html('');
self.$alerts.prepend(data.responseText);
}
},
complete: function(){
// reset button
self.$modal_confirm.removeClass('disabled').html(
self.modal_confirm_original_text);
}
});
}
window.ModalForm = ModalForm;
// define plugin
$.fn.modalForm = function(){
var self = this;
return self.each(function(){
var el = this;
var _ = new window.ModalForm($(el));
$.data(el, 'modalform', _);
});
}
// run plugin
$('[data-exsutils=modal-form]').modalForm();
})(jQuery);
</script>
Edit by #Daniel Arant:
A jsFiddle with a simplified, working version of the plugin code can be found here
Note by me: Please read the selected answer. This jsfiddle + adding var self = this will give you a complete picture of the problem and a good way around it.
The source of your problem is the line self = this in the ModalForm constructor. Since you did not use the keyword var before self, the JavaScripts interpreter thinks that self is a property of the global window object and declares it as such. Therefore, each time the ModalForm constructor is invoked, self takes on a new value, and all of the references to self in the event handlers created by the constructor for previous buttons then point to the new, most recent instance of ModalForm which has been assigned to the global self property.
In order to fix this particular problem, simply add the keyword var before self = this. This makes self a local variable rather than a global one, and the click event callback functions will point to their very own instance of ModalForm instead of the last instance that was assigned to self.
I created a working jsFiddle based on your code, which can be found here
I stripped down the plugin code to eliminate the ajax calls for the sake of simplicity. I also eliminated all of the uuid references. Once you get a reference to the modal as a jQuery object, you can use jQuery's .find() method to obtain references to the various components of the modal.
If you have any questions about my quick and dirty revision of your plugin

Categories