I have a list of date in my view, powered by my controller. I am using angular-translate to manage localisation in my all application but do not know how to deal with date object.
My HTML looks like this :
<div ng-repeat="date in nextDates">
<div class="day">{{date | date: 'EEEE'}}</div>
</div>
This code display a list a day : Monday, Tuesday, ... based on date which is a date object.
My first try was to use moment.js which is already used in this project, and deal really well with i18n. It works, but I had a lot of difficulty to update it when lang is changed by user since moment.js is not related to angular-translate.
I tried to implement it on my controller using an event to update my variable but didn't worked well. I would like to keep the object date in my view instead of having a moment object, I am sure there is a way not implementing it manually.
$scope.$on('translationChanged', function(event, lang) {
...
});
I would like to know if there is an easy way to solve this issue, my only idea is to generate a key for translation like DAY.0 for Monday, DAY.1 and translate it by myself but it sounds cheap. moment.js seems perfect for the job, but then how to link it with angular-translate ?
Thanks for reading.
OK so after some research I found a library on github called angular-moment which work fine for me.
First I import both js files + locale
<script src="bower_components/moment/moment.js"></script>
<script src="bower_components/angular-moment/angular-moment.js"></script>
<script src="bower_components/moment/locale/fr.js"></script>
<script src="bower_components/moment/locale/de.js"></script>
<script src="bower_components/moment/locale/it.js"></script>
Then I set up momentjs locale variable during my app mode config
var core = angular.module('app.core').config(configLang);
configLang.$inject = ['moment'];
/* #ngInject */
function configLang(moment) {
moment.locale('en');
}
I then can start using in my templates amFormat directive directly on my Date object
<div ng-repeat="date in nextDates">
<div class="day">{{date | amDateFormat:'dddd'}}</div>
</div>
If I want to change language in my app, I just use moment.locale(String); and my view is automatically updated.
$rootScope.$on('$authenticationStateChanged', function(event, userData, isAuthenticated) {
moment.locale(userData.currentLanguage.toLowerCase());
});
$scope.$on('translationChanged', function(event, lang) {
moment.locale(lang.toLowerCase());
});
I can then access all the power of moment.js in my angular app :D.
Related
I am using Angular translate for my app localization. I'd like to dynamically change the date format depending on the user's locale.
If the locale is French : format is dd/mm/yyyy
If the locale is English/US : format is mm/dd/yyyy
...and so on depending on the locale's default date format
How can I achieve this (cleanly) with Angular translate ?
I finally ended using moment.js and Angular moment.
Dates can be formatted to locale default with this:
<td>{{user.lastLogin | amDateFormat:'l LT'}}</td>
To change the moment locale, use the following:
amMoment.changeLocale(language);
Don't forget to import the moment locale files for the languages you wish to support:
<script src="assets/global/plugins/moment.min.js"></script>
<script src="jslib/angular-moment.min.js"></script>
<script src="jslib/moment/de.js"></script>
<script src="jslib/moment/es.js"></script>
<script src="jslib/moment/fr.js"></script>
<script src="jslib/moment/it.js"></script>
<script src="jslib/moment/pl.js"></script>
<script src="jslib/moment/ru.js"></script>
<script src="jslib/moment/zh-cn.js"></script>
And add angular moment module in your app:
var myapp = angular.module('myapp', ['angularMoment']);
Maybe I am out of date, but I don't think angular-translate has anything to do with localization. So here are my solution (yet it very clean)
If you are loading it only once per page reload use angular-i18n will be enough. Install and put js file into your HTML
bower install angular-i18n
<script src="/bower_components/angular-i18n/angular-locale_YOUR-LOCALE.js"></script>
If you want to load it dynamically angular-dynamic-locale :
bower install angular-dynamic-locale
<script src="myPath/tmhDynamicLocale.js"></script>
your js:
angular.module('myApp', ['tmh.dynamicLocale', ...])
angular.module('myApp').controller('myController', [..., 'tmhDynamicLocale',
function… {
tmhDynamicLocale.set('en');
}
])
NOTE, made sure you check the repo's readme for usage of localeLocationPattern(string)
Yeah there is a very easy way to do it..
Not sure if it's clean but can be made clean.
you can use interpolation provided by angular-translate, the problem is you can't use function inside interpolation string, but you can do something cool..
pass a function inside the object you're interpolating and call that function while interpolation
say you need to put in date
{{ 'date' | translate:{date:"28/01/2016"} }}
//instead of this
{{ 'date' | translate:'{date:"28/01/2016",func: func}' }}//func comes from scope.
and in your $translateProvider.translations
$translateProvider.translations('en',{
'date': "{{func(date)}}"
});
here is the plnkr
Please accept my apologies if i had any mistakes in my post. This is my first post here. But, i am not new to StackOverflow. Correct me if any.
I am using angular-bootstrap-datetimepicker library from the below url:
Link to library
I am currently embedding the calender on the page.
I am using angular.js, moment.js, grunt and bower. Absolutely no issue loading the calender and can even select a date and display the selected date as well.
Here is the sample code:
<div>
Selected Date: {{ data.embeddedDate | date:'yyyy-MMM-dd' }}
<datetimepicker data-ng-model="data.embeddedDate" data-datetimepicker-config="{ startView:'day', minView:'day'}" />
</div>
I am trying to highlight today's date automatically when the datetimepicker shows on the page.
As you can see, in the config options, i could set the default view and min view.
Note: I tried to mimic the working code (till now) in Plunkr but, its not showing the calendar. I added all libraries as well. Anyways, that's just for idea only. If i could get the Plunkr working, i will update again.
Here is the link to Plunkr.
Any suggestions (regarding highlight today date by default) will be appreciated.
To get the directive to show todays date by default, you can set the value of data.embeddedDate in the controller through its scope, like so:
$scope.data = { embeddedDate: new Date() };
Working Plunkr
I hope someone can help me with this issue.
I am trying to use the datepicker from the following link
The problem is that I want to be able to use a few features but don't know how.
1)I want to be able to unset a specific date from my angular controller
2)I want to be able to clear all the selected dates from the datepicker calendar.
http://bootstrap-datepicker.readthedocs.org/en/release/methods.html
Here's how my code looks:
<div class="col-md-3">
<h5>Pickup Dates</h5>
<!--Inline DatePicker-->
<div class="datepicker" ng-click="dateSelection()" ng-selected="selectedDates!=-1">
</div>
</div>
<script>
$('.datepicker').datepicker({
multidate: true,
todayHighlight: true,
format: 'dd/MM/yyyy'
});
</script>
My angular controller is as follow
$scope.dt = $('.datepicker').datepicker('getDates');
Then I have a function that gets triggered when a button is clicked.
Once the button is pressed, all dates are saved and then the selected dates
should clear from the calendar but instead a new calendar gets created.
$scope.createSearches=function() {
/*saving dates code*/
$('.datepicker').datepicker('clearDate')
}
I read the documentation and not sure how to use the clearDate event so if someone can help me with this and also how to unset specific dates from the controller, I will really appreciate that.
Thanks
Ok, I am playing around with Backbone, node.js, Underscore, Backbone Boilerplate so I have enough knowledge. Been asking questions like crazy as I still can't quite get my head around it. I am currently attempting to use the Underscore library with Backbone Boilerplate to make a very simple template which will allow me to pass in data; then when the model is updated, change the view which would change the template. I believe this is the correct way of doing it, instead of writing HTML code inside my JS file? Stop me if I'm wrong.
The Backbone Boilerplate has its template .fetch() system which I understand. However it would mean writing HTML in my JS I believe. So I wanted to use Underscore to simply pass information from the model to the view to the modules to render the template again (or I might be able to skip the view completely?).
My question is why won't this work, I think it's because I'm not changing it to JSON.
My HTML template:
<div>
<script id="rtemp" type="text/x-underscore-template">
<span><%= title %></span>
</script>
</div>
And the JavaScript:
define([
// Global application context.
"app",
// Third-party libraries.
"backbone",
"underscore",
"json2"
],
function(app, Backbone) {
var Attempt = app.module();
Attempt.Model = Backbone.Model.extend({});
Attempt.Collection = Backbone.Model.extend({});
Attempt.Views.Tutorial = Backbone.View.extend ({
template: "app/templates/attempt",
render: function(done) {
var tmpl = app.fetchTemplate(this.template);
//console.info(tmpl);
this.$el.html(tmpl({title: 'This is a title'}))
}
});
return Attempt;
});
When I inspect the element it shows in the <div> however it still has the template script tags around it so doesn't show on the page in HTML. I tried using json2 to convert it to JSON first, but that didn't seem to work unless I did something wrong. Is Underscore the best thing to use? I assumed so as it's a Backbone dependency. Or should I use something else. I just want to avoid writing HTML in my JS.
If I understand you right, you're ending up with this HTML:
<div>
<script id="rtemp" type="text/x-underscore-template">
<span>This is a title</span>
</script>
</div>
That's the right behavior based on the code you're using but that's clearly not the result you want.
The <script> wrapper for templates is used when you're embedding the template inside an HTML page. This is done so that the browser won't try to interpret your template as HTML and to keep the browser from trying to render it on its own. In such cases, you'd have the template embedded in the HTML page like this:
<!-- Some HTML stuff... -->
<script id="rtemp" type="text/x-underscore-template">
<span><%= title %></span>
</script>
<!-- Some other HTML stuff... -->
and you'd use it like this:
var t = _.template($('#rtemp').html());
var html = t(...)
The $('#rtemp').html() part extracts just the content of the template's <script> wrapper so _.template would only see <span><%= title %></span> and the final processed template would just be a simple <span>. For example: http://jsfiddle.net/ambiguous/dzPzC/
In your case, you're reading the entire <div><script>...</script></div> as the template and feeding that to _.template. The result is that tmpl({title: 'This is a title'}) still includes the <script>, the browser doesn't know what to do with a <script type="text/x-underscore-template"> so the <span> that you're interested in doesn't get rendered at all.
You don't need the <script> wrapper at all, that's only needed when you're embedding a raw template inside some HTML. Your template only needs the the content of your <script>:
<span><%= title %></span>
Demo: http://jsfiddle.net/ambiguous/QuwSX/
The argument that you're passing to the template function:
tmpl({ title: '...' })
is fine, the compiled template function just wants to see a JavaScript object. People talk about passing it JSON and often use the toJSON method to prepare data for the template but that's an abuse of terminology; the template really wants an object and JSON is, technically, a string.
We are working on a website like www.justdial.com .
We want to provide AutoComplete feature.
This autocomplete feature should be inline with the performance of justdial's.
We are using Indexes, please suggest more ways to provide superfast autocompletion.
I do not have much experience in the subject, but I have just implemented JQuery autocomplete with a medium sized list ~(1,000) entries, partial matches is enabled and it is still astoundingly fast. The only trick I've used is creating seperate js files for the lists and calling them first from the html. I also refrain from using the jquery on ready, so the complete list is bieng uploaded immediately. The actual calls to autocomplete are done on page ready. JQuery AutoComplete
Unfortunately I can't add the actual code because the data is sensitive, but its on the lines of..
<html>
<body>
Some HTML
<script type = "text/javascript" src = "collection.js"></script>
<script type = "text/javascript" src = "jquery.min.js"></script>
<script type = "text/javascript" src = "autocomplete.js"></script>
</body>
</html>
Collection .js would look something like
var collection = ["1","2","3", ... "1000"];
and AutoComplete.js would look like
$(document).ready(function(){
$("#form").autocomplete(collection, { matchContains:true });
});
I don't know what built in optimization Jquery has,but it seems pretty fast to me.
I believe even the Google "Suggest" feature used javascript, so it would just be a matter of keeping the lists sorted and dividing them efficiently? Maybe Huffman Coding could help?