【问题标题】:AngularJS ngInit with DateAngularJS ngInit 与日期
【发布时间】:2013-12-04 10:23:14
【问题描述】:

我正在使用 .NET MVC 进行编码,并希望将存储的 DateTime 对象作为控制器中 Date 对象的初始值传递给前端。

这是我尝试过的:

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

这似乎不起作用,我遇到了语法错误。

如何将 Date 对象作为范围变量的初始属性传入?

http://jsfiddle.net/xX8LJ/

更新

我忘记在我的代码示例中包含 Razor 代码。

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

【问题讨论】:

    标签: angularjs date angularjs-ng-init


    【解决方案1】:

    Angular 作用域不知道 Date

    尝试使用:

     $scope.Date = new Date();
    

    之后:

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

    演示 1 Fiddle

    作为您编辑的答案,

    Date重写为方法:

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

    和:

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

    演示 2 Fiddle

    【讨论】:

    • 太棒了,这正是我所需要的。谢谢!我发现ng-init="new Date()" 不起作用有点奇怪。任何想法为什么 Angular 不知道 JS Date 对象?
    • @DzulqarnainNasir 角度表达式不支持所有 JavaScript。
    【解决方案2】:

    另一种方法,在我的例子中,我在配置块的 $rootScope 中添加了一个 now 函数:

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

    然后可以这样使用:

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

    或者只是

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

    但我更喜欢使用 $root,因此我们可以确切地知道 now 函数的位置

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-24
      • 2015-11-03
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多