EmberJS displaying a formatted date - javascript

I'm trying to display a formatted date in EmberJS, but it's outputting a blank string.
{{#each}}
{{formatedDrawDate}}
{{/each}}
Output
<script id="metamorph-9-start" type="text/x-placeholder"></script>
<script id="metamorph-9-end type="text/x-placeholder"></script>
CoffeeScript
App.GroupsController = Ember.ArrayController.extend
formatedDrawDate: (->
moment(#get 'drawDate').format 'MMM Do YY'
).property('drawDate')
The data:
App.GROUPS = [
{
id: 1
drawDate: new Date()
},
# ...
]
My Route:
App.GroupsRoute = Ember.Route.extend
model: ->
App.GROUPS
I can see a cleanly formatted date in the console under the controller. I'm not sure why it's not displaying, though.

You need to use an itemController and put your formattedDrawDateproperty on it. Your code as it is now simply adds a single property to your controller - not to each of it's content.
App.GroupsController = Ember.ArrayController.extend
itemController: 'group'
App.GroupController = Ember.ObjectController.extend
formatedDrawDate: (->
moment(#get 'drawDate').format 'MMM Do YY'
).property('drawDate')
The documentation has a bit more info.

Related

Simple NG-IF filter not working with date but works with other data

So I have simple ng-repeat with an ng-if filter that does not seem to work for DATE but works for everything else (like cal, time). I don't know what I am doing wrong.
Controller:
$scope.twoWeeksForward=new Date();
$scope.twoWeeksForward.setDate($scope.twoWeeksForward.getDate() - 14);
$scope.sampledata = [
{ title: 'First Workout', time:1500 ,cal: 376, date: "2016-05-22T07:57:24.792Z"},
{ title: 'Second Workout', time:1100 ,cal: 20, date: 2016-05-22},
{ title: 'Third Workout', time:500 ,cal: 190, date: 01232016 },
{ title: 'Fourth Workout', time:4500 ,cal: 900, date: 01222016 }
];
HTML: (THIS PART DOES NOT WORK)
<div ng-repeat="items in sampledata" ng-if="{{items.date}}>{{twoWeeksForward}}">
I tested out some different syntax for the date field but nothing is working. Any help would be greatly appreciated:)
You don't use {{}} interpolation in ng-if ... it evaluates expressions directly. You are also missing a " to close the attribute value
Try
<div ng-repeat="items in sampledata" ng-if="items.date">
I think you would be better using a custom filter function on your ng-repeat, rather than a second directive (ngIf) on the same element:
View:
<div ng-repeat="items in sampledata | filter:isNextTwoWeeks">
Controller:
$scope.isNextTwoWeeks = function(item) {
return item.date && item.date > $scope.twoWeeksForward;
}
Note that the date comparison could do with some improvement and I'm not exactly sure of the logic you're trying to achieve so I just copied what you listed in your example.
Here is the correct format for ng-if.
<div ng-repeat="date in sampledata" ng-if="{{toDate(date.date)< twoWeeksForward}}">
You need to convert the date in the scope variable to date format as currently it is not in it so follow this
and add toDate function in controller
$scope.toDate = function(date) {
return new Date(date);
}

Filtering results in real time with AngularJS and MomentJS

I have an ng-repeat listing results but I'm aiming to only display elements containing today's date.
My current setup can do it, but needs a page reload to redefine the time variable and thus filter the results.
To be honest I'm not sure that such real-time filter (when is 00.00 the list becomes empty automatically) can be accomplished, so I'd be very grateful if you could shed some light into the issue.
Here's my current layout:
<div class="row msf-row"
ng-repeat="record in recordlist | filter: search | filter: record.date = dateJson "
ng-class="{ 'msf-cancelled': record.cancelled}">
<div class="col-md-1">{{record.date}}</div>
<div class="col-md-1"><strong>{{record.car}}</strong></div>
<div class="col-md-2">{{record.driver}}</div>
<div class="col-md-2">{{record.from}}</div>
</div>
And the relevant JS:
$scope.dateJson = moment().format("YYYY MM DD");
$scope.addRecord = function () {
$scope.recordlist.push(
{
date: $scope.dateJson,
car: $scope.carList.code,
driver: $scope.driverList.name,
from: $scope.locationList.place,
destination: $scope.locationList2.place,
pax: $scope.paxList
}
);
jsonToRecordLocalStorage($scope.recordlist);
};
So basically, the filter compares the $scope.dateJson with the object property record.date and filters the results, but of course date.Json is only loaded on page reload, not on real time.
Any inputs?
You can define your own filter function like here http://davidjs.com/2014/02/how-to-call-any-function-as-a-filter-in-angularjs/
this filter function would look something like this
$scope.filterRecordsByDate = function(record) {
var date = moment();
//reset to midnight
date.set('hours', 0).set('minutes', 0).set('seconds', 0);
//you might need to reset to midnight also the property 'record.date'
return record.date == date;
}
Then in your HTML
ng-repeat="record in recordlist | filter: search | filter: filterRecordsByDate "

Meteor: Get the post date

I'm having some difficulty to get the Date() to display the text with the date.
This is in my client.js:
Questions = new Meteor.Collection("questions");
Template.questions.items = function(){
return Questions.find({},{sort:{'submittedOn':-1}});
};
This is in clientserver.js:
Questions = new Meteor.Collection("questions");
Meteor.startup(function () {
});
Meteor.methods({
addQuestion : function(questionText){
console.log('Adding Question');
var questionId = Questions.insert({
'questionText' : questionText,
'submittedOn': new Date(),
'submittedBy' : Meteor.userId()
});
return questionId;
}
});
How can I post the text with the date in it?
You need a helper to format the date to your needs. moment is recommended for that. First add it:
mrt add moment
Then create a helper. See documentation for formatting options.
UI.registerHelper('formatDate', function(date) {
return moment(date).format('dddd, MMMM Do YYYY, h:mm:ss a');
});
Finally use the helper in a template:
<template name="questions">
{{#each items}}
{{formatDate submittedOn}}
{{/each}}
</template>

Having an issue with adding zulu time and date to popCalendar.js

I have this application I am implementing the new version of popCalendar.js with and I have added the zulu time and date function. I am not sure what I have wrong here. I have been banging my head against a wall. The console gives me this:
Uncaught TypeError: Object # has no method 'popCalendar'
Now the pages are generated with a python templating library and this is the snippet that creates the calendar:
class DateField(TextField):
"""
A field with a date widget as the input (which provides a browseable way to select the date)
"""
properties = TextField.properties.copy()
Base.addChildProperties(properties, Display.Label, 'calendarTypeLabel')
properties['isZulu'] = {'action':'setIsZulu', 'type':'bool'}
properties['hideTypeLabel'] = {'action':'formatDisplay.call', 'name':'hide', 'type':'bool'}
properties['dateFormat'] = {'action':'classAttribute'}
def __init__(self, id, name=None, parent=None):
TextField.__init__(self, id, name, parent)
self.userInput.style['width'] = '7.5em'
self.dateFormat = "dd-mmm-yyyy"
layout = self.addChildElement(Layout.Horizontal())
layout.addClass("FieldDescription")
self.calendarLink = layout.addChildElement(Display.Image(id + "CalendarLink"))
self.calendarLink.addClass('Clickable')
self.calendarLink.addClass('hidePrint')
self.calendarLink.setValue('images/calendar_icon.gif')
self.calendarLink.addJavascriptEvent('onclick', CallBack(self, "jsOpenCalendar"))
self.calendarTypeLabel = layout.addChildElement(Display.Label())
self.calendarTypeLabel.style['margin-left'] = "4px;"
self.calendarTypeLabel.style['margin-right'] = "4px;"
self.calendarTypeLabel.style['display'] = "block;"
self.setIsZulu(False)
self.formatDisplay = layout.addChildElement(Display.Label())
self.connect('beforeToHtml', None, self, '__updateDisplay__')
def setIsZulu(self, isZulu):
"""
If set to true the calender will use the zulu date
"""
self.isZulu = isZulu
if isZulu:
self.calendarTypeLabel.setText("Z")
else:
self.calendarTypeLabel.setText("LCL")
def __updateDisplay__(self):
if not self.editable():
self.calendarLink.hide()
self.formatDisplay.setText(self.dateFormat)
def jsOpenCalendar(self):
"""
Returns the javascript that will open the calender clientside
"""
if self.isZulu:
calendarType = "zulu"
else:
calendarType = "lcl"
return ("%sCalendar.popCalendar(this, '%s', '%s')" %
(calendarType, self.userInput.fullId(), self.dateFormat))
Factory.addProduct(DateField)
Here is the popCalendar.js I have been working on:
http://snipt.org/AfNh5
Last here is a sample of the HTML that is in my application:
<img src="images/calendar_icon.gif" style="float:left;" name="dateCalendarLink" value="images/calendar_icon.gif" class="Clickable hidePrint WEBlock" onclick="zuluCalendar.popCalendar(this, 'date', 'dd-mmm-yyyy')" id="dateCalendarLink" />
I got it :) I just needed zuluCalendar.show() instead of zuluCalendar.popCalendar() like so:
<img src="images/calendar_icon.gif" style="float:left;" name="dateCalendarLink" value="images/calendar_icon.gif" class="Clickable hidePrint WEBlock" onclick="zuluCalendar.show(this, 'date', 'dd-mmm-yyyy')" id="dateCalendarLink" />

Ember.js property and ArrayController in template

I've got a setup like this in Ember:
App.ListObject = Ember.Object.create({
knownThings: function() {
var ot = this.openThings.get('content');
var ct = this.closedThings.get('content');
var kt = ot.concat(ct);
var known = Ember.ArrayController.create({content: kt});
return known;
}.property(),
openThings: Ember.ArrayController.create({
content: []
}),
closedThings: Ember.ArrayController.create({
content: []
}),
})
Basically, known things is the combined arrays of openThings and closedThings. I can't seem to figure out how to iterate over knownThings in the template. Just doing
{{#each App.ListObject.knownThings }}
Does not work as the property needs to be accessed like App.ListObject.get('knownThings') but that doesn't work in the template unless I'm doing something terribly wrong. Iterating over the other attributes in the template does work (open and closed things)
So, how would you iterate over knownThings in the template?
Slight Modifications needed...
Firstly,
knownThings: function() {
//use get to retrieve properties in ember, Always !
var ot = this.get('openThings').get('content');
//var ot = this.get('openThings.content') if you are using latest ember
var ct = this.get('closedThings').get('content');
//var ot = this.get('closedThings.content') if you are using latest ember
var kt = ot.concat(ct);
var known = Ember.ArrayController.create({content: kt});
return known;
//Add dependencies to keep your knownThings in sync with openThings & closedThings if at all they change in future
}.property('openThings', 'closedThings')
Coming to Handlebars iterate using
//you forgot content property, and in handlebars you don;t need to use get, dot operator is enough
{{#each App.List.knownThings}}
Let me know if this works...
Update
Working Fiddle...
Unless I didn't understand what you're saying, I think you should have ListObject extending Em.ArrayController instead of Em.Object. Also, if your property depends on content, it should be .property('content.#each'). If you're using the router, your template should look like {{#each thing in controller.knownThings}} and you use {{thin.something}}, if not using router, then {{#each item in App.listObject.knownThings}}. Also, openThings and closedThings don't seem to be correct and the way you're accessing them is wrong too.
I didn't write a fiddle for this specific case cause I don't really know what you're trying to do, but take a look at this fiddle, specifically at App.ResourcesController and the template 'resources-view':
Controller:
// ...
App.ResourcesController = Em.ArrayController.extend({
content: [],
categories: ['All', 'Handlebars', 'Ember', 'Ember Data', 'Bootstrap', 'Other'],
categorySelected: 'All',
filtered: function() {
if(this.get('categorySelected') == "All") {
return this.get('content');
} else {
return this.get("content")
.filterProperty(
"category",
this.get('categorySelected')
);
}
}.property('content.#each', 'categorySelected'),
filteredCount: function() {
return this.get('filtered').length;
}.property('content.#each', 'categorySelected'),
hasItems: function() {
return this.get('filtered').length > 0;
}.property('filteredCount')
);
// ...
Template:
<script type="text/x-handlebars" data-template-name="resources-view">
<h1>Ember Resources</h1>
{{#view Bootstrap.Well}}
The following is a list of links to Articles, Blogs, Examples and other types of resources about Ember.js and its eco-system.
{{/view }}
{{view Bootstrap.Pills contentBinding="controller.controllers.resourcesController.categories" selectionBinding="controller.controllers.resourcesController.categorySelected"}}
<i>{{controller.filteredCount}} Item(s) Found</i>
{{#if controller.hasItems}}
<ul>
{{#each resource in controller.filtered}}
<li>
<a {{bindAttr href="resource.url"
target="resource.target"
title="resource.description"}}>
{{resource.htmlText}}
</a>
</li>
{{/each}}
</ul>
{{else}}
{{#view Bootstrap.AlertMessage type="warning"}}
Couldn't find items for {{controller.categorySelected}}
{{/view}}
{{/if}}
</script>

Categories