Datepicker value into string in Angularjs - javascript

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.

Related

Updating date in controller not reflected in input type=date

In AngularJS, I have on the DOM side:
<input class="form-control" type="date" ng-model="scope.status.date"
ng-change="scope.reloadDay()" ng-model-options="{debounce:200}">
In the back I have a function:
scope.changeDate = function() {
var current_date = scope.status.date;
current_date.setDate(current_date.getDate() - 1);
scope.status['date'] = current_date;
}
This results that indeed scope.status.date is updated, but in the input box it stays the same.
What is happening here?
Construct a new Date:
$scope.changeDate = function() {
var current_date = $scope.status.date;
current_date.setDate(current_date.getDate() - 1);
$scope.status.date = new Date(current_date);
};
This will trigger the $render() function of the ngModelController.
The DEMO
angular.module("app",[])
.controller("ctrl", function($scope) {
$scope.status = {date: new Date()};
$scope.changeDate = function() {
var current_date = $scope.status.date;
current_date.setDate(current_date.getDate() - 1);
$scope.status.date = new Date(current_date);
};
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
<input class="form-control" type="date" ng-model="status.date"
ng-model-options="{debounce:200}">
<br>
<button ng-click="changeDate()">Change Date</button>
</body>
Would have never thought of this that this triggers the render(). May I ask how you found this in the documentations? What did you look for?
From the Docs:
$render();
Since ng-model does not do a deep watch, $render() is only invoked if the values of $modelValue and $viewValue are actually different from their previous values. If $modelValue or $viewValue are objects (rather than a string or number) then $render() will not be invoked if you only change a property on the objects.
— AngularJS ngModelController API Reference - $render
For more information, see
How does data binding work in AngularJS?
AngularJS Developer Guide - Scope $watch Depths
Please check a date format, date format should be "yyyy-mm-dd"

Save state of ng-change local scope in Datepicker

I have come across what seems like a very simple issue, but I cannot figure out how to fix it. I posted this question originally, but it seems the issue is with the scope.
So basically, this is what is happening:
I have a datepicker inside a form. When the user selects a date, ng-change will trigger and it calls the function setDate(date).
In debug mode, I confirmed that the selected data indeed is passed to the function.
Inside the function, $scope.simStartDate variable is assigned this value and I can see its value changing.
However, when I later go to submit the form, $scope.simStartDate is back with its original initialized value.
I have put a breakpoint at the initialization $scope.simStartDate = new Date(), but it does not hit. Meaning that the variable is not initialized again.
I have tried using a $scope variable in the ng-model, but still the same issue.
This makes me think that ng-change creates a local scope and updates a local variable, which I cannot access later. Is my understanding correct? If not how can I fix this?
This is my HTML:
<div class="row" ng-controller="DashboardParamsFormCtrl">
<div class="col-sm-6">
<div class="form-group">
<label for="inputFirstName">Simulation start date</label>
<p class="input-group">
<input type="text" class="form-control"
uib-datepicker-popup="{{format}}"
datepicker-options="options"
ng-model="date"
ng-change="setDate(date)"
is-open="opened" ng-required="true"
close-text="Close"
alt-input-formats="altInputFormats"
show-button-bar="true" />
<span class="input-group-btn">
<button type="button" class="btn btn-default"
ng-click="open()">
<i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
</p>
</div>
</div>
This is the JS:
angular.module('BlurAdmin.pages.dashboard')
.controller('DashboardParamsFormCtrl', DashboardParamsFormCtrl);
/** #ngInject */
function DashboardParamsFormCtrl(baConfig, layoutPaths, baUtil, $scope)
{
$scope.ParamsFormBtnClicked = function()
{
console.log("Date: " + $scope.simStartDate);
}
$scope.open = open;
$scope.opened = false;
$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[0];
$scope.options = {
showWeeks: false
};
function open() {
$scope.opened = true;
}
$scope.simStartDate = new Date();
$scope.date = new Date();
$scope.setDate = function(startDate)
{
$scope.simStartDate = startDate;
}
}
})();
Thank you.
your passing new date(); without value, it will get current date. you should pass ng-model value inside new date();
like this.
$scope.simStartDate = new Date(date);
$scope.date = new Date(date);
hope this link will help you too plnkr

Angular copy a unix date to an angular/js date

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>

Datepicker ui-bootstrap setting value from model

I'm using the ui-bootstrap datepicker for my angular form. When I get the json from the database and set the value on the form the Date shows on the input but I can't submit because the input does not recognise the value from the scope, and I have to pick again the dates. I'll explain better:
This is my datepicker options in the controller that I copied from the documentation:
$scope.today = function() {
$scope.dt = new Date();
};
$scope.today();
$scope.clear = function() {
$scope.dt = null;
};
$scope.open = function( $event ) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.open2 = function( $event ) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened2 = true;
};
$scope.dateOptions = {
formatYear: 'yy',
startingDay: 1
};
$scope.formats = [ 'dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate' ];
$scope.format = $scope.formats[ 0 ];
My edit input is like this:
<div class="input-group"><input name="StartDate" type="text" class="form-control" popup-placement="top-left" datepicker-popup="{{format}}" is-open="opened" close-text="Close" ng-model="period.StartDate" id="StartDate" required />
<span class="input-group-btn">
<button type="button" class="btn btn-default calendar-input" ng-click="open($event)"><i class="fa fa-calendar"></i></button>
</span></div>
For debug purpose I showed the $scope.period.StarDate and at the beginning the date shows without quotes, but if choose again on the picker it shows with quotes.
What I tried was to filter the data before show it on the view like this:
$scope.period.StartDate = $filter('date')($scope.period.StartDate, 'dd-MMMM-yyyy');
The date is show it fine on the input and does let me submit it, but it saves only 0000-00-00 on the database. How do I filter the date from the json for the datepicker can recognize the data?
UPDATE
The data Type on the database is "date" only, and when I do the query the json brings the date like this: 2017-07-30T00:00:00.000Z
Even if I don't put required on the datepicker, it expect a date before doing the submit.

Date is not being formatted properly as requested; angularjs

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' }}"

Categories

Resources