AngularJS ngInit with Date

Dzulqarnain Nasir picture Dzulqarnain Nasir · Dec 4, 2013 · Viewed 15k times · Source

I'm coding in .NET MVC and would like to pass a stored DateTime object to the front-end as an initial value for a Date object in a controller.

Here's what I've tried:

ng-init="params.datetime = new Date()"

This doesn't seem to work, and I'm getting a syntax error.

How can I pass in a Date object as an initial property for a scope variable?

http://jsfiddle.net/xX8LJ/

UPDATE

I forgot to include the Razor code in my code sample.

ng-init="params.datetime = new Date('@Model.DepartureTime.ToString("s")')"

Answer

Maxim Shoustin picture Maxim Shoustin · Dec 4, 2013

Angular scope doesn't know about Date

Try to use:

 $scope.Date = new Date();

and after:

<div ng-controller="myController"
     ng-init="params.datetime = Date"
 >Current time: {{params.datetime}}</div>

Demo 1 Fiddle

As an answer for your EDIT,

rewrite Date as method:

$scope.Date = function(arg){
   return new Date(arg);
};

and:

 <div ng-controller="myController" 
      ng-init="params.datetime = Date('Tue Feb 18 2013 00:00:00 GMT+0200 (CEST)')"
  >Current time: {{params.datetime}}</div>

Demo 2 Fiddle