I am trying to get the date in formate of dd/MM/yyy and pass it on to my URI, the date is being passed but not in the format requested.
Here is my HTML code:
<script type="text/ng-template" id="getnewplaces.html" class="users">
<h1>{{message}}</h1>
<form name="myform" id="myform1" ng-submit="fetch()">
<input type="date" ng-model="date" value="{{ 'date' | date: 'dd/MM/yyyy' }}" />
<div>
<center>
<button type="submit" >Fetch</button>
</center>
</div>
</form>
<ul ng-repeat="newUser in newUsers">
<li>{{newUser}} </li>
</ul>
</script>
Angular Controller:
yApp.controller('NewPlacesCtrl', function ($scope, $http) {
$scope.fetch = function () {
var formdata = {
'date': this.date
};
var inserturl = 'http://websitelink/getnewusers?date=' + this.date;
$http.get(inserturl).success(function (data) {
console.log(formdata);
$scope.newUsers = data;
console.log(inserturl);
console.log(data);
$scope.message = 'List of New places';
})
}
});
This is my console out put:
Object {date: "2014-07-24"}
/getnewusers?date=2014-07-24
The filter you're using in your markup only modifies the view - not the actual model.
To apply the filter to the date in the contoller, inject $filter and use it:
yApp.controller('NewPlacesCtrl', function($scope,$http,$filter) {
$scope.fetch= function(){
var formdata = {'date' : $filter('date')(this.date, 'format') };
...
}
});
Also, using this.date will not be able to reflect in the view - you should use $scope.date in order to do that. And, the markup should then be value="{{ date | date: 'dd/MM/yyyy' }}"
Related
I'm trying to get datepicker value into a string or usable format for passing as a parameter to a get method. However,
the get method i tried always give an error, what is the best way to convert a datepicker value into a string?
<div ng-app="getserviceApp" ng-controller="getserviceCtrl">
<button ng-click="FunctionLoadData()">Load Data</button>
<input type="date" ng-model="from_date" />
<input type="date" ng-model="to_date" />
<script type="text/javascript">
var app = angular.module('getserviceApp', [])
app.controller('getserviceCtrl', function ($scope, $http) {
var FromDate = new Date($scope.from_date.selectedDate);
var ToDate = new Date($scope.from_date.selectedDate);
There are some discrepancies in the ng-models and the name of your $scope variables.
In your controller you should have something like
app.controller('getserviceCtrl', function ($scope, $http) {
$scope.from_date = new Date();
$scope.to_date = new Date();
$scope.loadData = function(){
console.log($scope.from_date.toISOString().split('T')[0])
console.log($scope.to_date.toISOString().split('T')[0])
//prints the dates in yyyy-MM-dd format
}
}
And in your HTML
<div ng-app="getserviceApp" ng-controller="getserviceCtrl">
<button ng-click="loadData()">Load Data</button>
<input type="date" ng-model="from_date" />
value = {{from_date | date: "yyyy-MM-dd"}}//Display the date
<input type="date" ng-model="to_date" />
value = {{from_date | date: "yyyy-MM-dd"}}
</div>
I think mistake is from_date.selectedDate. Use just model from_date
Here is working stackblitz.
I am having an issue where ng-model-options isn't reflecting the changes I need it to.
For example, in the snippet below if you enter 4:00 pm into both time inputs you'll see the UTC output is different - the first is 6 and the second is 8. This is expected. However, the issue occurs when I select +0800 using the dropdown. Since this updates the timezone variable, both time inputs should now display 8 when I enter 4:00 pm since the first input should now use the timezone variable (as specified in its ng-model-options). However this isn't happening. Even after I clear the input and re-enter the time manually it still shows the incorrect time. How can I make the timezone option in ng-model-options use a dynamically changing variable such as timezone?
See issue below:
angular.module('myApp', [])
.controller('myController', function($scope) {
$scope.timezones = ['+1000', '+0800'];
$scope.timezone = $scope.timezones[0];
$scope.time = '';
$scope.eightTime = '';
});
angular.element(document).ready(() => {
angular.bootstrap(document, ['myApp']);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<div ng-controller="myController">
<select ng-model="timezone">
<option ng-repeat="timezone in timezones" ng-value="timezone">{{timezone}}</option>
</select>
<p>Selected Timezone: {{timezone}}</p>
<input type="time" ng-model="time" ng-model-options='{timezone: timezone}' />
<p>Using dropdown T.Z of '{{timezone}}': {{time.getUTCHours()}}</p>
<input type="time" ng-model="eightTime" ng-model-options="{timezone: '+0800'}">
<p>Hardcoded '+0800': {{eightTime.getUTCHours()}}</p>
<!-- ^^^ This should be the output when '+0800' is selected in the dropdown -->
</div>
As per the documentation -
The ngModelOptions expression is only evaluated once when the
directive is linked; it is not watched for changes. However, it is
possible to override the options on a single ngModel.NgModelController
instance with NgModelController#$overrideModelOptions()
I have changed some of the lines to make it work for you :)
angular.module('myApp', [])
.controller('myController', function($scope) {
$scope.timezones = ['+1000', '+0800'];
$scope.timezone = $scope.timezones[0];
$scope.time = '';
$scope.eightTime = '';
$scope.$watch('timezone',function(v){
$scope.time = '';
$scope.myForm.time.$overrideModelOptions({'timezone': $scope.timezone});
//this will update the options whenever the timezone will be changed.
})
});
angular.element(document).ready(() => {
angular.bootstrap(document, ['myApp']);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-controller="myController">
<form name="myForm">
<select ng-model="timezone" ng-options="timezone for timezone in timezones">
</select> <!-- ng-options is the correct way to provide options to the select dropdown -->
<p>Selected Timezone: {{timezone}}</p>
<input type="time" name="time" ng-model="time" ng-model-options='{timezone: timezone}' />
<p>Using dropdown T.Z of '{{timezone}}': {{time.getUTCHours()}}</p>
<input type="time" ng-model="eightTime" ng-model-options="{timezone: '+0800'}">
<p>Hardcoded '+0800': {{eightTime.getUTCHours()}}</p>
<!-- ^^^ This should be the output when '+0800' is selected in the dropdown -->
</form>
</div>
You will find more details about $overrideModelOptions here - https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$overrideModelOptions
Edited:
You can achieve it by creating a separate directive.
**For versions >1.6.2 **
angular.module('myApp', ['kcd.directives'])
.controller('myController', function($scope) {
$scope.timezones = ['+1000', '+0800'];
$scope.timezone = $scope.timezones[0];
$scope.time = '';
$scope.eightTime = '';
});
angular.module('kcd.directives', []).directive('kcdRecompile', ['$parse', function($parse) {
'use strict';
return {
transclude: true,
link: function link(scope, $el, attrs, ctrls, transclude) {
var previousElements;
compile();
function compile() {
transclude(scope, function(clone, clonedScope) {
// transclude creates a clone containing all children elements;
// as we assign the current scope as first parameter, the clonedScope is the same
previousElements = clone;
$el.append(clone);
});
}
function recompile() {
if (previousElements) {
previousElements.remove();
previousElements = null;
$el.empty();
}
compile();
}
scope.$watch(attrs.kcdRecompile, function(_new, _old) {
var useBoolean = attrs.hasOwnProperty('useBoolean');
if ((useBoolean && (!_new || _new === 'false')) || (!useBoolean && (!_new || _new === _old))) {
return;
}
// reset kcdRecompile to false if we're using a boolean
if (useBoolean) {
$parse(attrs.kcdRecompile).assign(scope, false);
}
recompile();
}, typeof $parse(attrs.kcdRecompile)(scope) === 'object');
}
};
}]);
angular.element(document).ready(() => {
angular.bootstrap(document, ['myApp']);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.0/angular.min.js"></script>
<div ng-controller="myController">
<div kcd-recompile="timezone">
<select ng-model="timezone" ng-options="timezone for timezone in timezones">
</select> <!-- ng-options is the correct way to provide options to the select dropdown -->
<p>Selected Timezone: {{timezone}}</p>
<input type="time" name="time" ng-model="time" ng-model-options="{timezone: timezone}"/>
<p>Using dropdown T.Z of '{{timezone}}': {{time.getUTCHours()}}</p>
<input type="time" ng-model="eightTime" ng-model-options="{timezone: '+0800'}">
<p>Hardcoded '+0800': {{eightTime.getUTCHours()}}</p>
<!-- ^^^ This should be the output when '+0800' is selected in the dropdown -->
</div>
</div>
Reference Post - Dynamically Setting ngModelOptions in Angular
When the user clicks the button I want it to copy the vm.checkin (unix date) to the angular type=date field.
<input type="date" ng-model="vm.receiptForm.paidDate" id="receiptPaidDate">
<button ng-click="vm.receiptForm.paidDate = (vm.checkin * 1000) | date:'yyyy-MM-dd HH:mm:ss Z'">
<span class="size-tiny">Copy Date</span>
</button>
Is that possible to do? I cant seem to make it work.
The model for input[type=date] must always be a Date object, but date filter formats date to a string based on the provided format. You just need to convert your timestamp to a date as described here and then assign it to vm.receiptForm.paidDate.
UPDATE: as an option you can create your custom filter to achieve the desired functionality, see the code snippet below:
var module = angular.module("demo", []);
module.filter('tsToDate', function () {
return function (timestamp) {
return new Date(timestamp);
};
});
module.controller('Demo', [function Demo() {
var vm = this;
vm.checkin = 1529442000000;
vm.receiptForm = {
paidDate: ''
};
}]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="demo" ng-controller="Demo as vm">
<div>
<button ng-click="vm.receiptForm.paidDate = (vm.checkin | tsToDate)">Copy Date</button>
</div>
<input type="date" ng-model="vm.receiptForm.paidDate" />
<code>
{{ vm.receiptForm }}
</code>
</div>
UPDATE:
I have added additional code for clarification, which is annotated with * NEW *.
I was asked to clarify what this code is doing. A series of data is inputted into a collection called posts. On the postsList template the code is outputted when the timeToEnable field is less than the current time, which allows us to delay posts based on a specified date using this javascript time picker. The issue I have resides in /client/posts/post_edit.js where I am trying to set the value of one of the pickers from data in the collection which I don't know how to retrieve in javascript but I do in html simply using {{fieldHere}} and using the postsList template helper.
Hopefully this new code and info helps.
ORIGINAL QIUESTION.
I have a form that submits 5 fields in a posts collection. I have a edit page that, auto populates the tile, and content. However I have two separate Date/Time pickers. There is a function available to me to properly set the Date/Time pickers with the specific posts data when I am on the edit page. I cant output Date/Time data the usual way using {{date}} because it is stored in a particular format 2015-05-25T17:50:00.000Z I have created separate fields in the collection that separates day, month, year for do so using datepicker function.
This function will allow me to set the Date picker.
picker.set('select', new Date(year, month, date));
My Issue resides in getting the year, month and date data, based on the id that the post I am editing is using. I can place them in html using {{title}}, however I don't know how I would identify the id, and grab that post in the collection, and allow me to use picker.set like above.
Here is my code that I think will explain best what I have so far.
client
/client/posts/post_submit.js
Template.postSubmit.events({
'submit form' : function(e){
e.preventDefault();
var post = {
title: $(e.target).find('[name=title]').val(),
postContent: $(e.target).find('[name="postContent"]').val(),
timeToEnable: new Date(year, month, day, hours, minutes),
timeDisplay : timeDisplay,
year : year,
month : month,
day : day,
hours : hours
};
////console.log(post.timeToEnable);
Meteor.call('postInsert', post, function(error, result) {
// display the error to the user and abort
if (error){
return alert(error.reason);
}
// show this result but route anyway
if (result.postExists){
alert('This link has already been posted');
}
Router.go('postPage', {_id: result._id});
});
}
});
/client/posts/posts_list.html * NEW *
<template name="postsList">
<div class="posts page">
{{#each posts}}
{{> postItem}}
{{/each}}
</div>
</template>
/client/posts/post_item.html * NEW *
<template name="postItem">
{{> dashboard}}
<article>
<div class="post">
<div class="post-content">
<h1>{{title}}</h1>
<h3>{{timeDisplay}}</h3>
<p>{{{postContent}}}</p>
View
{{#if ownPost}}<a class="editPost" href="{{pathFor 'postEdit'}}">Edit</a>{{/if}}
</div>
</div>
</article>
</template>
/client/posts/posts_list.js * NEW *
Template.postsList.helpers({
posts: function() {
//return Posts.find({}, {sort: {submitted: -1}});
//
var data = new ReactiveDict();
data.set("now", new Date());
return Posts.find({timeToEnable: {$lt: data.get("now")}});
}
});
/client/posts/post_edit.html
<template name="postEdit">
{{> dashboard}}
<div class="container">
<form id="editForm">
<div class="postTitle">
<label class="titleLabel">Press Release Title.</label>
<div class="input">
<input name="title" id="title" type="text" value="{{title}}" placeholder=""/>
</div>
</div>
<div class="postTime">
<label class="titleLabel">Pick A time to post</label>
<div class="input">
<input class="timepicker" name="" id="" type="text" value="Click for a Time to Post" placeholder=""/>
</div>
</div>
<div class="postDay">
<label class="">Pick A Date to post</label>
<div class="input">
<input class="datepicker" name="" id="" type="text" value="Click for a Date to Post" placeholder=""/>
</div>
</div>
<div>
<div class="textarea">
<label class="contentLabel">Press Release content.</label>
<!-- <input name="postContent" id="postContent" type="text" value="" placeholder="Enwave has released a..."/> -->
<textarea name="postContent" id="postContent" type="text"></textarea>
</div>
</div>
<div id="submit">
<input type="submit" value="Submit"/>
</div>
<div class="deletePost">
<a class="btn btn-danger delete" href="#">Delete post</a>
</div>
</form>
</div>
</template>
This is where I want to retrieve the post fields for year, month, date. So I can set the picker to that date, all based off the specific post ID.
/client/posts/post_edit.js
This is the crucial part I need to output the fields from the collection here based on its specified id
Template.postEdit.rendered = function(){
picker.set('select', new Date(year, month, day));
}
lib
This Route outputs code to the html when using {{title}}.
/lib/router.js
Router.route('/posts/:_id/edit', {
name: 'postEdit',
data: function() { return Posts.findOne(this.params._id); }
});
lib/collections/posts.js * NEW *
Posts = new Mongo.Collection('posts');
Posts.allow({
update: function(userId, post) { return ownsDocument(userId, post); },
remove: function(userId, post) { return ownsDocument(userId, post); },
});
Posts.deny({
update: function(userId, post, fieldNames) {
// may only edit the following two fields:
return (_.without(fieldNames, 'title', 'postContent','timeToEnable','timeDisplay','year','month','day','hours').length > 0);
}
});
Meteor.methods({
postInsert: function(postAttributes) {
check(Meteor.userId(), String);
check(postAttributes, {
title: String,
postContent: String,
timeToEnable: Date,
timeDisplay:String,
year: Number,
month: Number,
day: Number,
hours: Number
});
var user = Meteor.user();
var post = _.extend(postAttributes, {
userId: user._id,
author: user.username,
submitted: new Date()
});
var postId = Posts.insert(post);
return {
_id: postId
};
}
});
server
~/server/publications.js`
Meteor.publish('posts', function() {
return Posts.find();
});
So I would like to grab the collection fields for posts into postEdit when the template is rendered, which will set the value of day input picker.
Thanks for help in advance.
This is what ended up working for me in the end.
client
/posts/post_edit.js
Template.post_edit.rendered = function(){
var year = (postObject.year);
var month = (postObject.month) -1;
var day = (postObject.day);
var hours = (postObject.hours);
var $input = $('.datepicker').pickadate();
var $inputTime = $('.timepicker').pickatime();
// Use the picker object directly.
var picker = $input.pickadate('picker');
var pickerTime = $inputTime.pickatime('picker');
picker.set('select', new Date(year, month, day));// Get on screen image
pickerTime.set('select', [hours,0]);// Get on screen image
}
lib
/lib/router.js
Router.route('/posts/:_id/edit', {
name: 'postEdit',
data: function() {
postObject = Posts.findOne(this.params._id);
return postObject;
}
});
i have a controller
function TestCtrl($scope)
{
var contentFromJson = 'Hi! this is <b>Bold</b> and <i>Italic</i>';
var dateFromJson = '/Date(1394526738123)/';
$scope.Date = dateFromJson;
$scope.Content = contentFromJson;
}
and a markup
<div ng-app>
<div ng-controller="TestCtrl">
Date is {{Date | date : 'MMM d, y'}}
<p>{{Content}}</p>
</div>
</div>
and i expect a result that parse the date to MMM d, y but the problem is the result from json Date is something like this /Date(000000000)/ i don't know the name of the format. :) and also, the html tags are printed as plain text..
Check this jsFiddle for testing
JsFiddle
Thanks in advance..
What's happening is, you're trying to parse the Date with the '/Date()/' text in it. So you have to extract the numbers first, then use the filter.
Controller:
function TestCtrl($scope)
{
var contentFromJson = 'Hi! this is <b>Bold</b> and <i>Italic</i>';
var dateFromJson = '/Date(1394526738123)/';
var regexPattern = /\d+/g;
$scope.Date = dateFromJson.match(regexPattern)[0];
$scope.Content = contentFromJson;
}
As for the html. Use ng-bind-html-unsafe (angularjs 1.1.1)
<div ng-app>
<div ng-controller="TestCtrl">
Date is {{Date | date : 'MMM d, y'}}
<p ng-bind-html-unsafe="Content"></p>
</div>
</div>
jsfiddle: http://jsfiddle.net/9NBLB/
edit, here's another way:
https://stackoverflow.com/a/2316066/769083
$scope.Date = new Date(parseInt(dateFromJson.substr(6)));
EDIT
Initialize App and Controller:
var app = angular.module('MyApp', []);
app.controller('TestingCtrl', ['$scope', function ($scope) {
$scope.Content =
[
{ Date : '/Date(1394526738123)/', Message : 'Hi! <b>Bold</b>' },
{ Date : '/Date(1394526738143)/', Message : 'Hi! <i>Italic</i>' }
];
$scope.ParseDate = function (dt) {
return new Date(parseInt(dt.substr(6)));
}
}]);
Custom Directive uses $observe to read the attribute value then uses element.html() to write the html out:
app.directive("showHtml", function() {
return {
restrict: 'A',
scope: {showHtml: '#'},
link: function(scope, element, attrs) {
attrs.$observe('showHtml', function() {
element.html(scope.showHtml);
});
}
}
});
Html:
<div ng-app="MyApp">
<div ng-controller="TestingCtrl">
<div ng-repeat="content in Content">
Message: <span show-html="{{content.Message}}"></span> <br />
Date: {{ParseDate(content.Date) | date : 'MMM d, y'}} <br /><br />
</div>
</div>
</div>
jsfiddle: http://jsfiddle.net/fXE5d/6/
Looks like you've got to evaluate the JSON date string first.
$scope.Date = eval(dateFromJson.match(/\/(.*)\//)[1]);
Use a library like momentjs to handle the parsing for you. See the fiddle here: http://jsfiddle.net/ahchurch/vkNk2/3/
<div ng-app>
<div ng-controller="TestCtrl">
Date is {{Date | date : 'MMM d, y'}}
<p>{{Content}}</p>
</div>
</div>
function TestCtrl($scope)
{
var contentFromJson = 'Hi! this is <b>Bold</b> and <i>Italic</i>';
var dateFromJson = '/Date(1394526738123)/';
$scope.Date = moment(dateFromJson).valueOf();
$scope.Content = contentFromJson;
}