unable to set custom time as initial value in moment-picker - angularjs

I am trying to set initial value of datepicker to be the time on the chart where the user clicked. The value is being stored in the variable used in ng-model but the it still displays the placeholder instead.
<input class="form-control" ng-init="vm.input" ng-model="vm.input" ng-model-options="{ updateOn: 'blur' }" placeholder="Click here to select a date"
moment-picker="vm.input" style="width:25em;height:25px;" format="LL LTS">
in controller I am passing the value to be displayed initially:
scope.vm.input = moment(xScale.invert(newData[0])).format("ddd MMM D YYYY HH:mm:ss z");//Sun Feb 18 2018 05:16:29
Am I missing something ? I tried the solution given in this question: How to set today date and time as default in angular-moment-picker . But it didn't work for me.

Your mistake is using scope and vm as this together in controller, description is:
<div ng-controller="ctrl as vm">
{{vm.input}}
</div>
app.controller("ctrl", function() {
var vm = this;
//do not use scope.vm, vm is scope for this controller
vm.input = "Hello World";
})
var app = angular.module("app", []);
app.controller("ctrl", function() {
var vm = this;
vm.input = moment().format("ddd MMM D YYYY HH:mm:ss z");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl as vm">
<input class="form-control" ng-init="vm.input" ng-model="vm.input" ng-model-options="{ updateOn: 'blur' }" placeholder="Click here to select a date"
moment-picker="vm.input" style="width:25em;height:25px;" format="LL LTS">
</div>

Related

How to detect focus on Angular 1

I am having multiple input text in form and on ng-focus I am calling a method let's say GetFieldName().
I my angular.js how can I detect that method having the focus on first field or second.
How can I validate that withing getFieldName() method to get field which have focus on it.
The best solution is to make angularJS directive to get the attrs
or to make the validation
https://docs.angularjs.org/guide/forms
This is solution with controller and $event to get the name attribute from element
var myApp = angular.module('myApp',[]);
myApp.controller('formCtrl', ['$scope', function($scope) {
$scope.text = "sample text";
$scope.getName = function(event){
$scope.text = event.target.getAttribute('name');
};
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp">
<form ng-controller="formCtrl">
{{text }}
<input type="text" name="text1" ng-focus="getName($event)">
<input type="text" name="text2" ng-focus="getName($event)">
<input type="text" name="text3" ng-focus="getName($event)">
<input type="text" name="text4" ng-focus="getName($event)">
</form>
</div>

issue with converting date and time to millisecond format in angularjs

I am working on an angularjs web application which uses REST layer to communicate with the backend. I have to display the date and time of a job but I receive it in milliseconds format. How do I convert the value to display the date and time on the UI.
1479982860000 // input
11/24/16 //output date
10:21 AM //output time
Both have to be stored in DataModel.date and DataModel.time.
Also the user enters a date and a time which I have to combine and send it in the same milliseconds format to the REST layer. How do I do that?
<input type="time" id="exampleInput1" ng-model="DataModel.time"
placeholder="HH:mm:ss" required/>
<input type="date" id="exampleInput2" ng-model="DataModel.date"
placeholder="yyyy-mm-dd" required/>
I have to combine the two and send it as Datamodel.date in the controller. Please help.
According to the documentation, you can convert the value in your controller.
$scope.date = new Date($scope.DataModel.time);
$scope.date= $filter('date')(new Date($scope.DataModel.time), 'yyyy-mm-dd');
and the view:
<input type="date" id="exampleInput2" ng-model="date" placeholder="yyyy-mm-dd" required/>
Don't forget to add $filter in your dependencies:
app.controller('YourController', ['$scope','$filter', function($scope, $filter) {
}]);
[This may work for your issue]
https://docs.angularjs.org/api/ng/filter/date
Here is a simple example to achieve what you need,
use
(new Date($scope.milli_seconds)) to get the full date.
(new Date($scope.milli_seconds)).toDateString() to get the date from it
(new Date($scope.milli_seconds)).toTimeString() to get the time from it
(new Date($scope.milli_seconds)).getTime() to convert bact to milliseconds
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
"milliseconds" : {{milli_seconds}} <br>
"full_date" : {{full_date}} <br>
"date" : {{date}} <br>
"time" : {{time}} <br>
"millisecondsreverse" : {{milli_seconds_reverse}} <br>
<br><br>
<input type="time" id="exampleInput1" ng-model="DataModel.time"
placeholder="HH:mm:ss" required/>
<input type="date" id="exampleInput2" ng-model="DataModel.date"
placeholder="yyyy-mm-dd" required/>
<input type="submit" ng-click="submit_values()" value="getmilliseconds"/> <br>
<span ng-if="milli">Your milliseconds: {{milli}}</span>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.DataModel = {}
$scope.milli_seconds = 1479982860000;
$scope.full_date = (new Date($scope.milli_seconds))
$scope.date = $scope.full_date.toDateString()
$scope.time = $scope.full_date.toTimeString()
$scope.milli_seconds_reverse = $scope.full_date.getTime();
$scope.submit_values = function()
{
date = new Date($scope.DataModel.time).toTimeString()
time = new Date($scope.DataModel.date).toDateString()
date_time = (new Date($scope.DataModel.date).toDateString())+" "+ (new Date($scope.DataModel.time).toTimeString())
alert(new Date(date_time).getTime());
$scope.milli = new Date(date_time).getTime();
}
});
</script>
</body>
</html>
Please run the above snippet
You can just convert it into different formats you like, using the filters.
Here is a fiddle
Have a look at moment.js
Add configuration in your JS file
/*Configuration to change the date format*/
angular.module('myapp')
.config(function($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return date ? moment(date).format('DD/MM/YYYY') : '';
};
$mdDateLocaleProvider.parseDate = function(dateString) {
var m = moment(dateString, 'DD/MM/YYYY', true);
return m.isValid() ? m.toDate() : new Date(NaN);
};
})
Change the format which ever way you want
var newFormatDate =moment(oldFormatDate).format();
EDITS
If you want to set specific timezone,
moment().tz("America/Los_Angeles");
MOMENT.JS DOCS
Also look at timezone identifier

Bind to a property which is a formula exposing another

In Angular (1.3), I want to be able to enter a dob field of my person object and this has another property called age which calculates the age based on the dob.
So I have the field to enter dob as:
<div class="form-group">
<input class="form-control" type="date" ng-model="player.dob" placeholder="DD/MM/YYYY" />
</div>
and I display some of the information that the user types, as they type (name, sex, description etc) but when the user enters the dob, I want to automatically display age like this:
<div>{{player.age}}</div>
How can I do that?
Thanks
I don't know if it's what you're looking for, but if I'm correct you can create a custom filter to display the age based on the dob input, as below:
angular.module('app', [])
.controller('mainCtrl', function($scope) {
$scope.player = {};
})
.filter('ageFilter', function() {
return function(dob) {
var ageDifMs = Date.now() - new Date(dob).getTime();
var ageDate = new Date(ageDifMs);
return Math.abs(ageDate.getUTCFullYear() - 1970);
};
});
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<div class="form-group">
<input class="form-control" type="date" ng-model="player.dob" placeholder="DD/MM/YYYY" />
</div>
<hr>
<div ng-if="player.dob" ng-bind="player.dob | ageFilter"></div>
</body>
</html>
you can use ngChange
<div class="form-group">
<input class="form-control" type="date" ng-model="player.dob" ng-change="calculateAge()" placeholder="DD/MM/YYYY" />
and then in your controller:
$scope.calculateAge = function(){
//do the calculations you want
}

Passing values to ng-model from ng-repeat

I have a form that passes its inputs to ng-model before storing to the database. One of which is a dynamic value (pre-generated code) that is taken from its database table.
<div class="form-group" ng-repeat="codes in response | filter: {branch: formData.branches.alias, taken: 0} | limitTo: 1">
<input class="form-control" type="text" name="code" ng-model="formData.code" ng-value="codes.code" readonly="" />
</div>
Theoretically, once the ng-model gets the value, it then passes it to the insert call for the database to store it along with the rest of the fields.
scope.processForm = function(isValid){
scope.$submitted = true;
if(isValid && state.$current=='registration.signupapp') {
http.post("server/insert.php",{'code': scope.codes.code, 'fullname': scope.formData.name, 'instagram': scope.formData.igname, 'email': scope.formData.email, 'mobile': scope.formData.mobile, 'location': scope.formData.location.type, 'branch': scope.formData.branches.branch}).success(function(data, status, headers, config){
console.log("inserted successfully");
});
state.go('registration.success');
} else if(!isValid) {
//alert("Please make sure that you entered everything correctly.");
}
};
Unfortunately, this does not work. 1) I was told that you cannot simply pass an ng-value to an ng-model inside an input[text]. 2) Even if in the case that the value is passed to ng-model, I am not sure what to call inside the controller as scope.codes.code nor scope.formData.code do not seem to work and gets either a not defined error or 404.
In a nutshell, how do I:
Get the value generated by ng-repeat as set to limitTo:1.
Store it to ng-model in real-time (as this is very dependent on a
dynamic dropdown).
Pass the value of ng-model back to the controller.
Send it back to the server and store it to the database.
I guess ng-init should help you out here.
Change your code segment from:
<div class="form-group" ng-repeat="codes in response | filter: {branch: formData.branches.alias, taken: 0} | limitTo: 1">
<input class="form-control" type="text" name="code" ng-model="formData.code" ng-value="codes.code" readonly="" />
</div>
to:
<div class="form-group" ng-repeat="codes in response | filter: {branch: formData.branches.alias, taken: 0} | limitTo: 1" ng-init="formData.code=codes.code">
<input class="form-control" type="text" name="code" ng-model="formData.code" readonly="" />
</div>
This is really contrived, but here's a very simplified demo:
var app = angular.module('demo', []);
app.filter('myFilter', function(){
return function(data){
return data[0];
};
});
app.controller('MainCtrl', ['$scope', '$filter', function($scope, $filter){
var myfilter = $filter('myFilter');
$scope.response = ['001', '002', '003', '004', '005'];
$scope.items = ['Item 1', 'Item 2', 'Item 3']
$scope.formData = {};
$scope.$watch('formData.select', function(newval){
if (newval === 'Item 1') {
$scope.formData.code = myfilter($scope.response);
} else {
$scope.formData.code = '';
}
});
}]);
#import "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css";
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="demo" ng-controller="MainCtrl">
<pre>formData.code = {{formData.code || "No Code for this Item"}}</pre>
<div class="form-group">
<label>Select a Value: <em>Choose Item 1 to update formData.code</em></label>
<select class="form-control" ng-model="formData.select" ng-options="item as item for item in items"></select>
</div>
<div class="form-group">
<label>formData.code:</label>
<input class="form-control" type="text" name="code" ng-model="formData.code" />
</div>
</div>
You have the response already, so rather than use ng-repeat, just add the value to the formData.code on the controller. If you need to use a custom filter, you can pass in the $filter service as a dependency to your controller.
Edit:
I didn't notice the part about the formData.code being dependent on another form value, so I updated the demo to include a $watch function.

AngularJS: How to trigger function call when a form field gets focus

I want my controller to perform some action when a user clicks in a form field (when the form field gets focus). How can I do this? See this plunker.
Here is my controller:
angular.module('myApp', [])
.controller('AppCtrl', ['$scope',
function($scope) {
$scope.field1 = "Default text";
$scope.focus = false;
$scope.formFieldJustGotFocus = function() {
$scope.focus = true;
// Do all the stuff I need to happen when the form has just gotten focus
}
}
]);
And here is the view:
<body ng-app="myApp" ng-controller="AppCtrl">
<h3>Testing</h3>
<p>I want to perform some action in the controller when a form field gets focus. How can I best achieve this?</p>
<form name="myForm">
<input type="text" name="field1" ng-model="field1">
</form>
<p>Form field has focus: {{focus}}</p>
</body>
You can use the ngFocus directive. The inverse is ngBlur.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<input type="text" ng-focus="isFocused = true" ng-blur="isFocused = false">
<p ng-if="isFocused">Focus !</p>
</div>
<input type="text" name="field1" ng-model="field1" ng-focus="formFieldJustGotFocus()">
use like this ng-focus
Try ng-focus.
See more info:
https://docs.angularjs.org/api/ng/directive/ngFocus
use -> ng-focus
<input type="text" name="field1" ng-model="field1" ng-focus="formFieldJustGotFocus();">
this plunker
in the code he had written the function formFieldJustGotFocus(), but it was not bound to the focus event

Resources