Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to AngularJS Date from json

i'm a newbie in angularjs i'm trying to bind a date property to a input(text) but i don't know how to format the date.

my json object controler:

$scope.datasource = {"prop1":"string data", "myDateProp":"\/Date(1325376000000)\/"}

my view:

<input type="text" ng-model="datasource.myDateProp" />

as result, i get the string "/Date(1325376000000)/" on my textbox.

how can i format this date?

like image 841
Flavio CF Oliveira Avatar asked Oct 11 '12 10:10

Flavio CF Oliveira


1 Answers

What you need to do is have a look at http://docs.angularjs.org/api/ng.filter:date which is a filter that is available in angular by default.

It seems that you are passing additional stuff with the date. See the scenario here. ( /Date(*)/ ) . Except for the stuff in * everything else is not necessary to parse the date and the default angular filter wont be able to parse it. Either strip these additional stuff from the model, or alternatively, you could write your own filter to strip them on input.

EDIT :

Have a look at http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController ( and the example that is defined there! ). If you intend on reusing this in multiple places, I suggest you to do it in the method that ngModelController describes. Create a new directive and implement $render and $setViewValue on the ngModel.

If you just want to do this in one place, then an alternate would be to define a new model for the input. Something like

$scope.dateModel = "";

and use it

<input type="text" ng-model="dateModel" ng-change="onDateChange()"/>

In your controller, you will have to do something like :

$scope.$watch("datasource.myDateProp",function(newValue){

    if(newValue){
        convert(newValue);
    }
});

function convert(val){
    //convert the value and assign it to $scope.dateModel;
}


$scope.onDateChange = function(){
// convert dateModel back to the original format and store in datasource.myDateProp.
}
like image 59
ganaraj Avatar answered Nov 08 '22 06:11

ganaraj