Parsing from /Date(1487185200000)/ to date format - angularjs

I want to convert this type of object to date format as (Sat 10/4/2016 5:03 PM)
how can I do that of input type /Date(1487185200000)/ using angularJs
May json is something like this
[{
"Post_Id": 1,
"Posts_Date":/Date(1487185200000)/,
"Post_Description": "Test",
},
{
"Post_Id": 2,
"Posts_Date": /Date(1487358000000)/,
"Post_Description": "Test",
}
]
This is my script in my controller
$http.post("/Home/GetPostData").then(function (d) {
$scope.Posts = d.data;
});
And this is my View
<div class="post_content" ng-repeat="p in Posts">
<h3> {{p.Post_Id}}</h3>
{{p.Post_Description}}
{{p.Posts_Date}}
</div>
And the output is somthing like this
1
Test
/Date(1487185200000)/
2
Test
/Date(1487358000000)/
want to convert my date as Standard format like (Sat 10/2/2016 4:50 PM) etc

If you are also interested in getting a Javascript Date (not just displaying), you can convert the JSON formmatted date/time information like this:
function parseJsonDate(jsonDateString){
return new Date(parseInt(jsonDateString.replace('/Date(', '')));
}
Credit

You need to visit this Angular Date filter
html
{{p.Posts_Date|removeBaces| date: 'medium'}}
js
myApp.filter('removeBaces', function() {
return function(input) {
return input.replace('/Date(','').replace(')/','');
}
});

Related

Looping through json array of objects to display unique property with all its data

I am new to angular and need help for the below-
I have a json data as follows in my json file:
{
"records":
[
{
"date":1619038000,
"name":"Susan",
"status":"available"
},
{
"date":1419038000,
"name":"Vinay",
"status":"not available"
},
{
"date":1419038000,
"name":"Ajay",
"status":"available"
}
],
"record2":[
{
"date":1419037000,
"name":"Soumya",
"status":"not available"
},
{
"date":1326439320,
"name":"Harsh",
"status":"available"
},
{
"date":1419031000,
"name":"Gopi",
"status":"available"
}
]
}
this is my js file:
angular.module("myApp",[]).controller("Control",function($scope,$http){
$http.get('myData.json').
success(function(data){
$scope.tableData = data.records;
});
});
I want to display data in the table from the json in such a way that all data having the same "date" are grouped together and shown jst one date in the table.Could you pls help me with this.I want it as follows:
date name status
16th april susan available
17th april vinay not available
ajay available
To show the result: GroupBy date, follow the below steps.
STEP 1: Add Moment JS library to your HTML file.
http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js
STEP 2: Update your controller file as below:
var app = angular.module("myApp",[]);
app.controller("Control",function($scope,$http){
$http.get('myData.json').
success(function(data){
$scope.tableData = data.records;
});
});
app.filter('groupBy', function() {
return _.memoize(function(items, field) {
return _.groupBy(items, field);
}
);
});
STEP 3: To render the data add the following code to your HTML file.
<ul>
<li ng-repeat="(date, persons) in tableData | groupBy:'date'">
{{date * 1000 | date:"dd.MM.y"}}
<ul>
<li ng-repeat="person in persons">
{{person.name}}
</li>
</ul>
</li>
</ul>
Codepen Link
You need to use 'ng-repeat'
Here is a tutorial and examples for your guide
https://www.w3schools.com/angular/ng_ng-repeat.asp
For date, here is some guidance
https://www.w3schools.com/angular/ng_filter_date.asp

How to translate the input text (datepicker) value dynamically using angular-translate?

I am using angular-translate to provide i18n to my application, I am able to translate labels, button-text etc. properly.
The problem I am facing is when I am trying to change the date according to the selected language locale. The date is selected from a date-picker.
the date is selected into an input element:
<input type="text" class="form-control" required="" ng-model="date" placeholder="{{ 'DATE_PLACEHOLDER' | translate }}" translate="{{ 'select_date'|translate:{date:date} }}"/>
the placeholder translation works perfectly, but no change happens to date format when I change the language.
I have created a plunkr describing the current scenario.
Plunker Link
Please suggest a way in which I can translate inserted values, or text in forms.
Also, I would like to know how to overcome the flicker of key values just before the page is loaded.
Add Italian locale, I copied it from http://forum.html.it/forum/showthread/t-2912577.html:
$.fn.datepicker.dates['it'] = {
days: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato", "Domenica"],
daysShort: ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab", "Dom"],
daysMin: ["Do", "Lu", "Ma", "Me", "Gi", "Ve", "Sa", "Do"],
months: ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"],
monthsShort: ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"],
today: "Oggi",
clear: "Cancella",
weekStart: 1,
format: "dd/mm/yyyy"
};
Add convert map for language codes from en_EN format to en:
// language codes convertor map
var convertorMap = {
'en_US': 'en',
'it_IT': 'it'
};
In your language switcher function, remove current datepicker and initialize a new one with new language, make sure to update date in new format as well:
$scope.switchLanguage = function (key) {
var dp = $('#datePicker');
// get current date
var currentDate = dp.datepicker('getDate');
// update datepicker with new locale
dp.datepicker('remove');
dp.datepicker({
autoclose: true,
language: convertorMap[key]
});
// restore current date according to the new locale
dp.datepicker('update', currentDate);
$translate.use(key);
};
To show view only when translation is ready, change your wrapper element (I used <body>) to look like:
<body ng-controller="Ctrl" class="ng-hide" ng-show="showView">
.....
</body>
and in your controller:
// will be fired when the service is "ready" to translate (i.e. loading 1st language)
$translate.onReady(function () {
$scope.showView = true;
});
ng-model directive on jQuery datepicker does nothing, so I removed it, and added ng-model update code to initial datepicker function:
$('#datePicker').datepicker({
autoclose: true
})
// update ng model
.on('changeDate', function(e) {
$timeout(function () {
$scope.date = $('#datePicker').datepicker('getUTCDate');
});
});
if you see in the console message like:
pascalprecht.translate.$translateSanitization: No sanitization strategy has been configured. This can have serious security implications.
it is said to be fixed in next releases: https://github.com/taigaio/taiga-front/issues/778
plunker: http://plnkr.co/edit/EGtHPG?p=preview

Dynamically add filter in ng-repeat

I am building a table where the rows and columns are built entirely based on the data that is sent to it.
I'm very close to having it work, I'm having trouble figuring out how to build a custom filter and pass in the filter patterns dynamically
The object that makes up the columns looks like
{ name: 'transactionDate', displayName: 'Date / Time', displayOrder: 1, filter: "date: 'MM/dd/yy hh:mm a'" }
The object that makes up the transaction for the rows looks like this:
{ transactionDate: '2015-06-11', transactionType: 'This Type', transactionAmount: 25 }
The HTML I have is this:
<td ng-repeat="col in columns">{{transaction[col.name] | dynamicFilter: col.filter}}</td>
The filter I currently have built is:
function dynamicFilter($filter) {
return function (value, filter) {
console.log(filter);
console.log(value);
var test = $filter(filter)(value);
return test;
}
}
Both filter and value are getting passed correctly. I'm having trouble figuring out how to apply the filter to the value before returning. A value that might be passed in would 2015-06-10T16:17:14 be and a filter that would be passed in could be date: 'MM/dd/yy hh:mm a' to create date/time filter. Or 21 and currency for a dollar value.
I would like to be able to use Angular's built in features in a similar way you could on the view
For these dynamic filters that have partial params (such as the format you're providing with date), you have to remove the param from the filter and apply it later.
So filter: "date: 'MM/dd/yy hh:mm a'", needs to be just filter: "date".
The additional constraint, MM/dd/yy hh:mm a, would be sent along with the value $filter(filter)(value, 'MM/dd/yy hh:mm a');
To do this generically, you can take advantage of apply. The Object can be:
{filter: { type: "date", params: ['MM/dd/yy hh:mm a'] } }
And the directive can have (assuming you send the params as well):
var filterFn = $filter(filter.type);
return filterFn.apply(filterFn, [value].concat(filter.params));
EDIT: here's a JSFiddle with two buttons, the first demonstrates your original approach with "date: 'MM/dd/yy hh:mm a'", and the second demonstrates applied approach that I outline above http://jsfiddle.net/4whemakt/
You can apply and return the filtered value conditionally in your dynamicFilter. Something like this
function dynamicFilter($filter) {
return function (value, filter) {
if (filter.indexOf('date:') !== -1) {
//Note: I am using moment js to format the date
return moment(value).format(filter.match(/'([^']+)'/)[1]);
}
else {
return $filter(filter)(value)
}
}
}
moment.js reference http://momentjs.com/

Using an OR conditional when using Angular filters

I just started working with Angularjs and I'm facing the following problem:
I get this kind of object from an API request:
{
"recid": "1576",
"title": "19th Century UK Periodicals",
"description": "Bevat ruim 180 gescande tijdschriften die full text doorzoekbaar zijn",
"type": "tek",
"tags": "Engeland",
"primair": "b:bio",
"secundair": "h:eng,h:ges",
},
And I need to filter by selecting data that belongs to 'primair' OR 'secundair' field, how could I do that since chaining uses a sort of AND intead of Or.
regards in advance,
Eduardo
The easiest way would be to use a custom filter function. In your controller you would define it like this:
function YourController ($scope) {
$scope.filterFn = function (v) {
return (v.primair === 'somevalue') || (s.secundair === 'someothervalue');
};
}
In your template you can use it like this:
<li ng-repeat="item in yourlist | filter:filterFn">{{item.title}}</li>

ng-repeat and nested array in json

i have some problems accessing some values stored in a json with the directive ng-repeat.
the json is formatted properly (checked it with a json checker) and it's called via $http service. unfortunately i can't change the format of json, retrieved through the wordpress-json-api plugin.
the json (with some cuts):
{
"status": "ok",
"count": 10,
"count_total": 24,
"pages": 3,
"posts": [
{
"id": 108,
"type": "sensor",
"slug": "ert",
"custom_fields": {
"sensor_id": [
"er"
],
"coords": [
"{\"address\":\"\",\"lat\":55.39979700000003,\"lng\":10.430533275390644,\"zoom\":12}"
]
}
}
//etc other posts following, json correct
Now i have a problem accessing the single values inside coords. i complained too about serializing data in db, but i'd like anyway to get lng and lat out of that array
<ul>
<li ng-repeat="post in sensor.posts">
<h4>name : {{post.id}}</h4> //ok
<h4>all custom fields : {{post.custom_fields}}</h4> //good-this-too
<h4>custom field lat : {{post.custom_fields.prova_coords[0]}}</h4> //works but can't go on
</li>
</ul>
the ouput of last line is:
custom field lat : {"address":"","lat":55.39979700000003,"lng":10.430533275390644,"zoom":12}
but now i'm stuck..can't retrieve single lat and long values
You need to use $scope.$eval(coordsString)
Here's a test: http://jsfiddle.net/mikeeconroy/Rnc7R/
var objString = "{\"address\":\"\",\"lat\":55.39979700000003,\"lng\":10.430533275390644,\"zoom\":12}";
$scope.coords = $scope.$eval(objString);
Then you can refer to coords.lat or coords.lng in your template like so:
<div ng-controller="myCoordsCtrl">
Lattitude: {{coords.lat}}<br>
Longitude: {{coords.lng}}
</div>
Since this is happening within an ngRepeat you may need to use an Angular filter to rectify the string on the fly
<li ng-repeat="post in sensor.posts | myRectifyCoordsFilter">
EDIT:
Don't use the filter like in the above example, using filters to modify $scope is not a good situation. You'll need to modify your $scope prior to using it in the ng-repeat
$http.get().success(function(data){
angular.forEach(data,function(val,key){
this.coords = $scope.$eval(val.coords[0]);
},data);
$scope.sensor = data;
});

Resources