14

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")')"
Dzulqarnain Nasir
  • 2,150
  • 1
  • 19
  • 16

2 Answers2

23

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

Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
  • 2
    Awesome, this is just what I needed. Thanks! I found it a bit strange that ``ng-init="new Date()"`` doesn't work. Any ideas why Angular wouldn't know about the JS Date object? – Dzulqarnain Nasir Dec 04 '13 at 10:42
  • @DzulqarnainNasir angular expressions do not support all of JavaScript. – Davin Tryon Dec 04 '13 at 10:48
1

Another way to do it, in my case I've added a now function in my $rootScope in a config block:

...
$rootScope.now = now;

/**
* returns now as a date
* 
* @function 
* @param arg {object} date arguments
* @returns {Date} now
*/
function now(arg) {
    return new Date(arg);
}
...

and then can be used like this:

<div ng-init="product.date = $root.now();"...

or just

<div ng-init="product.date = now();"...

but I prefer using $root so we know exactly where the now function is located

Samuel Poirier
  • 1,240
  • 2
  • 15
  • 30