As I can do Bootstrap alert, pressing a button to change language - javascript

I have a problem, which I try to do an alert when the visitor changes the language of the web, the alert is create but disappear, because that is changing the link by:
?locale=es || ?locale=en || http://localhost:3000/pages/index?locale=en
The default is in English, but the push the button, the alert your duration is for 0.5 seconds and disappear.
As I can make the alert remains until you delete it?
Note: Im use Ruby On Rails.
My Button:
<li> <%= t('menuLen')%></li>
Code My Alert:
<div class="container">
<center>
<div class="alert alert-success" id="successChangeEN" role="alert">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Success!</strong> Your Language is now English.
</div>
</center>
</div>
My JS:
<script>
bootstrap_alert = function() {}
bootstrap_alert.warning = function(message) {
$('#alert_placeholder').html('<div class="alert alert-success"><a class="close" data-dismiss="alert">×</a><span>'+message+'</span></div>')
}
$('#AlertEN').on('click', function() {
bootstrap_alert.warning('You change the language success!');
});
</script>
I hope to answer, thank you.

Here you have an example using cookies http://jsfiddle.net/0Lcofr6x/show/
Source Code Here: http://jsfiddle.net/0Lcofr6x/
Url is not changing due the fact fiddle does not accept dummy query string but trust me you are navigating to same page (reload).
$( document ).ready(function() {
$('#AlertEN').attr('href', window.location.href);
bootstrap_alert = function() {}
bootstrap_alert.warning = function(message) {
$('#alert_placeholder').html('<div class="alert alert-success"><button class="close" data-dismiss="alert">×</button><span>'+message+'</span></div>');
$('#alert_placeholder .close').unbind( "click" );
$('#alert_placeholder .close').on('click', function() { $('#alert_placeholder').hide();
$('.alert-success').show();
});
}
$('#AlertEN').on('click', function() {
$.cookie("changed_locale", "You change the language success!");
});
$('.alert-success').hide();
if ($.cookie("changed_locale") != null)
{
bootstrap_alert.warning('You change the language success!');
}
$.removeCookie("changed_locale");
});

Related

Is there any better way to show success alert message

I am trying to show Success message , once the data is updated in my application. Success function is working properly , but message is not getting generated. when I click on the save() button, small alert box will display, but message wont appear.
HTML : <div class="alert alert-success" ng-show="successmessage">{{cts.success_info}}</div>
Angular Js:
$scope.successmessage = function(){
$scope.cts = [];
$scope.cts.success_info = "Data Successfully got updated";
}
You defined successmessage as a function, but using it as a value.
If you need to display alert on success call of save function, use success function below. It creates an object with a message and isSuccess flag:
Html:
<div class="alert alert-success" ng-show="cts.isSuccess">{{ cts.message }}</div>
JS:
$scope.success = function() {
$scope.cts = {
isSuccess: true,
message: 'Data Successfully got updated'
};
}
Working demo
You can take advantage of *ngIf if want to display more then just simple string like below:
showMsg: boolean = false;
onSubmit() {
this.userService.createUser(this.addForm.value)
.subscribe( data => {
this.router.navigate(['list-user']);
this.showMsg= true;
});
}
then you can use showMsg boolean to show/hide dive like below
<div class="col-md-6">
<div ng-click=="onSubmit()">
<div class="row" *ngIf="showMsg">
<div class="col-xs-12">
<p class="alert alert-success">
<strong>Registration Success!</strong> Please click here to login!.
</p>
</div>
</div>
<button class="btn btn-success">Add user</button>
</div>
</div>
note that I am using some bootstrap classes for styling.
Yes function must return something . If you want a better option , you can use toast or popover .
Do this,
<div class="alert alert-success" ng-show='cts.showmsg == true'>{{cts.success_info}}</div>
You can use one boolean variable to show/hide message.
Angular Js:
$scope.successmessage = function(){
$scope.cts = [];
$scope.cts.success_info = "Data Successfully got updated";
$scope.cts.showmsg = true;
}
If you want to display in popup or modal, then there is best library in angular called ngDialog

Build input dynamically from View Model in an ajax response

I have a controller action that sends down a collection of ApiViewModel Types. Each view model represents a different API that can be executed server-side, and output the response in the browser through an ajax call using jquery. The server generates the HTML so all I have to do is insert the server-side HTML into the current page.
Some of the APIs can only execute if they are given some parameters. I'm trying to do this in a generic fashion. When the user clicks the run button, I display a model Bootstrap dialog. Within this dialog I'd like to provide the input options for the parameters on the API selected.
This is my HTML for the modal dialog
<div class="modal fade"
id="appParameters"
role="dialog"
aria-labelledby="appParametersLabel">
<div class="modal-dialog"
role="document">
<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="appParametersLabel"></h4>
</div>
<div class="modal-body" id="appDialogBody">
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
i have enough information to send to the server, letting the server know what API is going to be executed, and what View Model needs to go with it. What I'm not sure of though is how should I put together the HTML on the server side, so that I can send the HTML to the client and have the MVC validation attributes still work for client-side validation?
The javascript I'm using to send the data to the server, and add the servers HTML to the DOM is this. If no View Model is required, I just make a request to the server to execute the app and output the server-side response HTML. I think I don't need to do anything in regards to my Java Script below to handle the validation stuff; not sure though.
$('.btn-success').click(function () {
var button = $(this);
var appId = $(this).data("app");
var vmRequired = $(this).data("vm-required");
if (!vmRequired) {
var url = "/Home/RunApp?appId=" + appId;
$.get(url, function (data) {
$("div[data-app='" + appId + "']").html(data);
var buttonColumn = button.parent();
var appRow = buttonColumn.parent();
var hiddenRow = appRow.next()
hiddenRow.removeClass("hidden");
appRow.click(function () {
var hiddenColumn = hiddenRow.children().first();
var resultsDiv = hiddenColumn.children().first();
resultsDiv.empty();
hiddenRow.addClass("hidden");
$(this).off();
hiddenRow.off();
})
hiddenRow.click(function () {
var hiddenColumn = $(this).children().first();
var resultsDiv = hiddenColumn.children().first();
resultsDiv.empty();
$(this).addClass("hidden");
appRow.off();
$(this).off();
})
});
return;
}
var appName = $(this).data("app-name");
$('#appParametersLabel').html(appName);
$('#appParameters').modal({
keyboard: true,
backdrop: "static",
show: false,
}).on('show', function () {
$.get(url, function (data) {
$('#appDialogBody').html(data);
})
});
});
Do I just generate the HTML on the server side, like I would normally in the view? When the HTML is inserted into the DOM, will the validation all work correctly while using unobtrusive jquery validation?

AngularJS View does not update after model update

I have a <div> on my page for alert message:
<div ng-controller="PercentageOverrideController as ctrl">
<script type="text/ng-template" id="alert.html">
<div class="alert" style="background-color:#fa39c3;color:white" role="alert">
<div ng-transclude></div>
</div>
</script>
<uib-alert ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</uib-alert>
<button type="button" class='btn btn-default' ng-click="addAlert()">Add Alert</button>
</div>
In my Angular controller I have a variable $scope.alerts = [ ] and function which pushes a new alert message to an array:
$scope.showSuccess = function(){
$scope.alerts.push({type: 'success', msg: 'Threshold Overrided'});
};
$scope.showError = function(){
$scope.alerts.push({type: 'danger', msg: 'Error has been happened'});
};
After I make a request and get a response, I check in debug mode that the function was invoked and that a new value was added to the array. However it does not appear on my page.
I have a test button in my div:
<button type="button" class='btn btn-default' ng-click="addAlert()">Add Alert</button>
If I press this button, the alert appears on the page. If I try to invoke the same function:
$scope.addAlert = function() {
$scope.alerts.push({msg: 'Another alert!'});
};
within the code:
$scope.showSuccess = function(){
$scope.alerts.push({type: 'success', msg: 'Threshold Overrided'});
$scope.addAlert();
};
but the alert does not appear on page.
I assume that I should trigger somehow the view to show that update on page. What do you think guys?
Thank you!
You can use $scope.apply()
$scope.showSuccess = function(){
$scope.alerts.push({type: 'success', msg: 'Threshold Overrided'});
$scope.addAlert();
$scope.apply();
};
Instead of <div ng-controller="PercentageOverrideController as ctrl">
try <div ng-controller="PercentageOverrideController">
you need to run a digest loop.
$scope.$apply()
or alternatively
$scope.$digest()
should do it.

Why are the Ember component(s) for my notifications not being read/rendered?

I've been stumped on this issue all day and have exhausted all possible reasons I can think of. The problem is that my handlebar to display a notification if the user has one is not displaying.
As it is early on, I'm just testing it out by when I click 'Sign in' button, it sends a notification to the user (me in this case) just so I can see it working.
To put it simply...it doesn't work. I've attached an image showing the final result on a webpage, and it seems to comment out the handlebar line, and ignore it. And I've not a clue why.
I know the data is being read, as the other classes/componenets (the .js files, and other files) are able to return the data in the console. My 'main-header' components and 'main-footer' components renders/reads fine across all pages.
I'm also using a near-enough exact copy of another website's code that uses this. And it works perfectly. Originally I made some changes but earlier I copy-pasted everything I thought relevant, and it still didn't work.
Here is the HTML for the index.hbs (the homepage/page shown in the screenshot)
<div>
{{main-header}}
{{notification-list notifications=application.currentNotifications closeNotification='closeNotification'}}z
</div>
<!--Navbar - Home, About and Contact. Fixed position follows user down page-->
<header id="header" role="banner">
<!-- Navigation -->
</header>
<!--Main Body-->
<div class="container">
<br>
<br><br><br><br><br><br><br>
<button class="btn btn-primary btn-block btn-center" type="submit" {{action 'login'}}>
Sign In
</button>
<!--Footer containing copyright, logos and social media-->
{{main-footer}}
</div>
The Homepage's .js file;
App.IndexRoute = Ember.Route.extend({
model: function() {
}
});
App.IndexView = Ember.View.extend({
templateName: 'index'
});
App.IndexController = Ember.Controller.extend({
needs: ['application'],
currentNotifications: Ember.computed.alias("controllers.application.currentNotifications"),
actions: {
login: function() {
console.log(this.currentNotifications);
this.send( 'pushNotification', 'Message Sent', false );
}
}
});
The notification-list.hbs file (Btw, the original was made using '{{#each x in y}}' and I had to change that due to deprecation, but ultimately it should work the same I believe;
<div class="container notify">
<div class="row">
{{#each notifications as notification}}
{{#if notification.error}}
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true"
{{action 'closeAlert' notification}}>
×
</button>
<span class="glyphicon glyphicon-hand-right"></span> <strong>{{notification.title}}</strong>
<hr class="message-inner-separator">
{{#each notification.message as message}}
<p>
<b>{{message.field}}</b>{{#if message.value}}: {{message.value}}{{/if}}
</p>
{{/each}}
</div>
{{else}}
<div class="alert alert-info">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true"
{{action 'closeAlert' notification}}>
×
</button>
<span class="glyphicon glyphicon-ok"></span> <strong>{{notification.title}}</strong>
<hr class="message-inner-separator">
<p>{{format-text notification.message}}</p>
</div>
{{/if}}
{{/each}}
</div>
</div>
And the associated notificationlist's .js file;
App.NotificationListComponent = Ember.Component.extend( {
notifications: [],
lastLength: 0,
didInsertElement: function(){
if(this.notifications != null){
this.notifications.forEach(function(notification){
Ember.run.later( this, function () {
if ( this.notifications.indexOf( notification ) >= 0 ) {
this.send( 'closeAlert', notification );
}
}, 3000 );
}, this)
}
},
////DO NOT REFERENCE IN HANDLEBARS
timeout: function() {
var lastLength = this.get( 'lastLength' );
var notifications = this.get( 'notifications' );
//check it was an added notification, not a destroyed one
if ( notifications.length >= lastLength ) {
var index = notifications.length - 1;
if ( index >= 0 ) {
var notification = notifications[ index ];
Ember.run.later( this, function () {
if ( notifications.indexOf( notification ) >= 0 ) {
this.send( 'closeAlert', notification );
}
}, 3000 );
}
}
//update last length
this.set('lastLength', notifications.length);
}.observes('notifications.length'),
actions: {
closeAlert: function( notification ){
this.sendAction('closeNotification', notification);
}
}
});
Finally the app.js file. I've left some parts off that I don't think is relevant (such as the Adapter and store etc) if its needed lemme know though, but its pretty much the standard/default ones;
App.ApplicationController = Ember.Controller.extend({
currentNotifications: [],
notification: Ember.Object.extend( {
title: null,
message: null,
error: false
} ),
//Don't Call Directly, Use Route.Send to activate
pushNotification: function( message, error ) {
var currentNotifications = this.get( 'currentNotifications' );
var notification = new this.notification;
var test = error ? 'Failure' : 'Success';
notification.setProperties( {
title: test,
message: message,
error: error
} );
//Remove old message
if(currentNotifications.length >= 4) {
this.send('closeNotification', currentNotifications[0]);
}
currentNotifications.pushObject( notification );
},
closeNotification: function( notification ){
var currentNotifications = this.get( 'currentNotifications' );
var index = currentNotifications.indexOf(notification);
//remove notification
currentNotifications.removeAt(index);
},
updateCurrentPath: function() {
App.set('currentPath', this.get('currentPath'));
}.observes('currentPath')
});
The image showing the result of the above code. The highlighted line () is the line where the notification-list component is supposed to be
If this is all of your code (unmodified), it seems like you're just giving it a bad value. In the template, you pass the notifications like this:
notifications=index.currentNotifications
Again, assuming that this is all of your code, I can't see where a variable named index would come from. You should probably be using controller.currentNotifications.

AngularJS ng-show only triggering once

I have the following HTML
<div class="alert alert-danger col-sm-10 col-sm-offset-1" ng-show="showErrorMessage">
<button data-dismiss="alert" class="close" ng-click="closeErrorMessage()">
×
</button>
<i class="fa fa-check-circle"></i>
<strong>Error</strong> The following errors have occurred:
<div ng-repeat="error in createResp.Errors">{{error}}</div>
</div>
With the following inside my JavaScript
$scope.showErrorMessage = false;
$scope.search = function () {
var createOrderResp = myData.create($scope.request);
createOrderResp.$promise.then(function (r) {
$scope.createResp = r;
if ($scope.createResp.Errors.length > 0) {
$scope.showErrorMessage = true;
}
}, function (r) {
handleResourceError(r);
});
};
$scope.closeErrorMessage = function () {
$scope.showErrorMessage = false;
};
So everything works fantastic the first time through. If the response contains errors then the div is shown. However after clicking the close button closeErrorMessage() and then performing it again the error alert does not show up even though the showErrorMessage flag turns to true.
The issue is with data-dismiss. It will remove entire alert block. Therefore triggering ng-show with variable in scope won't help, since there won't be an html part, that will need triggering.

Categories

Resources