Display Date if valid Date using angular.isDate(value) - angularjs

Why can't I directly use angular.isDate in the Binding. Something like:
{{(angular.isDate(cdate.customStartDate)? cdate.customStartDate | date : format : timezone : 'Please select'}}

You need to expose isDate from the controller.
Like $scope.isDate = angular.isDate
If it isnt on the scope, it cannot be seen by your view.
But like what jsmtslch said, this logic would be better served in the controller. Something along the line of
$scope.isCorrectDate = function (targetDate){return angular.isDate(cdate.CustomStartDate))}
then you can use in your view
{{isCorrectDate(cdate.CustomStartDate) ? cdate.customStarteDate | date: format:timezone :'Please Select'

Related

converting date format in angularjs controller

i write the following coding to print the current date time
$scope.date = new Date();
and then i print the same using consol.log
console.log($scope.date);
and it is working fine
Tue Jan 24 2017 16:36:06 GMT+0530 (India Standard Time)
but now i want to change the date format and i want to print like
21-12-2016
can anybody help me here?
i used the conversion but i am unable to remember the page or the url of the page right now,
and stuck on this,
before i leave for the home today i thought of solving this issue
In controller you can do
$filter('date')(date, format, timezone)
to change the date format. And in html,
{{ date_expression | date : format : timezone}}
use this.
Like
$scope.formattedDate = $filter('date')($scope.currDate, "dd-MM-yyyy");
to print same on html
{{ currDate | date : "dd-MM-yyyy"}}
https://docs.angularjs.org/api/ng/filter/date
Following formats are supported by angular.
You can do this either in controller or in html page.
$scope.date = new Date();
The first one is :
$scope.date = $filter('date')($scope.date, 'dd-MM-yyyy');
Second one is :
{{date | date:'dd-MM-yyyy'}}
You can use the Angular date filter:
{{date | date: 'dd-MM-yyyy'}}
You can use the in-build js libraries functions i.e getDay(), getHours(), getMinutes(), getMilliseconds(). This functions will return you the corresponding date's individual components values.
e.g
var x = $scope.yourDateModelObj.getHours();
Likewise, you can get the date, month, years values.
return an integer value for hours.
Hope that helps

AngularJS orderby refining

I have a table of names starting with a title (Mr, Mrs, etc) and dates stored as strings plus some other data.
I am currently sorting it using
<tr dir-paginate="booking in bookingResults | orderBy:sortType:sortReverse | filter:searchPassenger | itemsPerPage: 15">
How could I refine my orderBy to sort names excluding the title (Mr, Mrs, etc) and dates as parsed dates not strings.
What would be best practice here?
EDIT :
I don't want to change the names in the model by the way - I want the format to remain "Mr Foo" and "Mr Bar" but when I sort them I want them to act as if they were just "Foo" and "Bar".
EDIT EDIT :
AngularJS 1.5.6
getting the right data in the right format
title & name
I'd use a regexp to pull the title from the name:
var regex = /((Dr\.|Mr\.|Ms\.|Miss|Mrs\.)\s*)/gmi
objName.replace(regex, '')
date
I'm assuming you're getting either a date object or a standard date string. If it's the latter, just create a Date object via new Date(incomingDateString). Then you can call:
objDate.getTime() //returns epoch in milliseconds
sorting
Some people might dislike this but I hate dirtying up view controllers with methods that NG directives need to use for things like ordering. Instead, I added some ng-flagged properties using ng-init on each row item. Then I can sort based off that. I didn't do it for the date in the example but you could extrapolate and apply.
ng-init w. ng-flagged properties
<tr ng-repeat="row in vc.listData | orderBy:vc.sortKey track by $index"
ng-init="row.$name = row.name.replace(vc.regexp, '')">
So in other words your objects go from this:
{
name:'Mr. Fred Rogers',
date:<date-object>
}
to this thanks to ng-init:
{
name:'Mr. Fred Rogers',
date:<date-object>,
$name:'Fred Rogers',
$date:1466192224091
}
And then via your sorting UI, you can set your $scope.sortKey to either $name or $date.
code pen
I made a sample in code pen but I did it with my template which is coffeescript and jade. You can probably figure out what I'm doing.
pen - http://codepen.io/jusopi/pen/aZZjgG?editors=1010
Ok, after some research, I found that the easiest solution is upgrading to AngularJS version 1.5.7 which introduces the comparator into the orderBy filter.
So I've changed my repeater to use an order by comparator
<tr dir-paginate="booking in Results | orderBy:Variable:TrueOrFalse:bookingComparator">
Variable is a string which I bound to the table headings so you can change the order by key, TrueOrFalse is a boolean which alternates between ascending and descending if you click the table heading and bookingComparator is my actual comparator.
My booking comparator looks like this
$scope.bookingComparator = function (a, b) {
var getTitle = /((Mrs|Mr|Mstr|Miss|Dr)\s*)/g;
var isDate = /(-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-)/g
if (getTitle.test(a.value)) {
var aName = a.value, bName = b.value;
return aName.replace(getTitle, '') < bName.replace(getTitle, '') ? -1 : 1
}
if (isDate.test(a.value)) {
var aDate = new Date(a.value), bDate = new Date(b.value);
return aDate.getTime() < bDate.getTime() ? -1 : 1
}
return a.index < b.index ? -1 : 1
}
The comparator is basically a function acting like the javascript .sort() method.
If the value contains a title (Mr, Mrs, etc) it is a name so I strip the titles and compare the actual names regardless of title.
If the variable matches a -Month- pattern, it's a date string and I compare the parsed date objects.
Hope this is helpful to someone, took me a while to figure out. I'm open to suggestions if you think there's a better way of doing this, and feel free to post an answer for people who want to use AngularJS =< 1.5.6

Angular filter for date in HTML

I am trying to filter the date using angular filter in HTML. But it is not working.
Here is my template code:
{{due_date | date:'MM/dd/yy'}}
The input is: {"due_date" : "2015-10-10 16:00:00.000+0000"}
The expected output is: 10/10/15
What mistake am I doing?
It happens becouse due_date is a String instead of a Date object.
You can "convert" it by doing (maybe you should put this into your controller):
var due_date_parsed = new Date(due_date);
parse your date like :
$scope.date = Date.parse(new Date());
in you code
Date.parse(jobDetails.trs_data.due_date)
if string is also in proper date format like '20140313T00:00:00' then this code will work perfectly fine. In other case you will have to convert/parse the string to date type.

Angular JS Date format filter inside Ng-Repeat not formatting

Actual Date coming from JSON
Need to format it as below .
Effective Date : 2010-08-31 (trim the time stamp)
End Date : 2010-08-31 (trim the time stamp)
Am using the below code for Formatting the date inside Ng-Repeat.
<li ng-repeat="product in data | startFrom:currentPage*pageSize | limitTo:pageSize"
ng-click="getAttributes(product)">
{{product.prod_start_date| date:'MM/dd/yyyy'}}
{{product.prod_end_date| date:'MM/dd/yyyy'}}
</li>
But it doesnt work still displays the same.
Should the Date be passed as new Date as shown in the below jsfiddle Example
http://jsfiddle.net/southerd/xG2t8/
Note sure how to do that inside ng-repeat.?? Kindly help me on this. Thanks in Advance
I created my own filter to address this.
The date filter cant take a string, needs a date object.
.filter('cmdate', [
'$filter', function($filter) {
return function(input, format) {
return $filter('date')(new Date(input), format);
};
}
]);
then you can do:
{{product.prod_start_date| cmdate:'MM/dd/yyyy'}}
I use moment.js for my UI date time handling (there even a nice angular-moment bower package as well)
http://momentjs.com
https://github.com/urish/angular-moment
usage:
<span>{{product.prod_start_date | amDateFormat:'MM/dd/yyyy'}}</span>
It has a bunch of other options as well with relative dates etc.
I have updated the controller that you showed in the fiddle and here is your updated filter
Here I made use of the $filter('date') which is a feature of Angular itself in order to format the date in the desired format.
Here is the controller:
function Scoper($scope,$filter) {
$scope.s = "2012-10-16T17:57:28.556094Z";
var dateObj = new Date($scope.s);
$scope.dateToShow = $filter('date')(dateObj,'yyyy-MM-dd');
console.log($scope.dateToShow);
}

How to extend or override existing filters in angularjs?

Is it possible to extend existing "standard" filters (date, number, lowercase etc)?
In my case I need to parse date from YYYYMMDDhhmmss format so I'd like to extend (or override) date filter instead of writing my own.
I prefer to implement the decorator pattern, which is very easy in AngularJS.
If we take #pkozlowski.opensource example, we can change it to something like:
myApp.config(['$provide', function($provide) {
$provide.decorator('dateFilter', ['$delegate', function($delegate) {
var srcFilter = $delegate;
var extendsFilter = function() {
var res = srcFilter.apply(this, arguments);
return arguments[2] ? res + arguments[2] : res;
}
return extendsFilter;
}])
}])
And then in your views, you can use both.. the standard output and the extended behavior. with the same filter
<p>Standard output : {{ now | date:'yyyyMMddhhmmss' }}</p>
<p>External behavior : {{ now | date:'yyyyMMddhhmmss': ' My suffix' }}</p>
Here is a working fiddle illustrating both techniques:
http://jsfiddle.net/ar8m/9dg0hLho/
I'm not sure if I understand your question correctly, but if you would like to extend functionality of existing filters you could create a new filter that decorates an existing one. Example:
myApp.filter('customDate', function($filter) {
var standardDateFilterFn = $filter('date');
return function(dateToFormat) {
return 'prefix ' + standardDateFilterFn(dateToFormat, 'yyyyMMddhhmmss');
};
});
and then, in your template:
{{now | customDate}}
Having said the above, if you simply want to format a date according to a given format this can be done with the existing date filter:
{{now | date:'yyyyMMddhhmmss'}}
Here is the working jsFiddle illustrating both techniques: http://jsfiddle.net/pkozlowski_opensource/zVdJd/2/
Please note that if a format is not specified AngularJS will assume that this is 'medium' format (the exact format depends on a locale). Check http://docs.angularjs.org/api/ng.filter:date for more.
The last remark: I'm a bit confused about the 'parse from' part of your question. The thing is that filters are used to parse an object (date in this case) to string and not vice verse. If you are after parsing strings (from an input) representing dates you would have to look into NgModelController#$parsers (check the "Custom Validation" part in http://docs.angularjs.org/guide/forms).

Resources