【问题标题】:Changing a rails datetime to string in Angular controller在 Angular 控制器中将 Rails 日期时间更改为字符串
【发布时间】:2014-09-26 06:53:11
【问题描述】:

我正在学习 angular,并将一个附加到 rails api。我正在使用角度{{example.date}} 在我的视图中渲染对象的日期。我假设按摩从我的 rails api 出来的 JSON 的最佳位置是在角度控制器中,但很难掌握如何做到这一点。这是我的设置:

Rails 控制器:

class ExampleController < ApplicationController
    def index
      render json: Example.all
    end

    def show
      render json: Example.find(params[:id])
    end
end

Angular 服务(coffeescript):

App.factory 'Example', ['$resource', ($resource)->
  $resource '/api/examples/:id', id: '@id'
]

Angular 控制器(coffeescript):

App.controller 'ExampleCtrl', ['$scope', 'Example', ($scope, Example) ->
  $scope.example = Example.query()
]

在我的 haml 视图中,所有这些基本管道都以ng-repeat告终:

  %div{"ng-controller" => "ExampleCtrl"}
        %ul
          %li{"ng-repeat" => "example in example"}
            %h3 {{example.date}}

我相信我在角度控制器中的Example.query() 正在返回一个包含所有数据的大型数组。我将如何在咖啡脚本中编写一个 each 循环来将所有日期时间(例如 Tue, 23 Sep 2014 00:00:00 UTC +00:00)转换为格式化日期?我已经在我的应用程序上连接了凉亭,如果有帮助,我可以安装 moment js。

谢谢

【问题讨论】:

  • 你试过 ng-filter 吗?我们可以使用过滤器修改我们的数据。您甚至可以格式化日期
  • 成功了。学习角度,不知道 ng-filter。漂亮,谢谢!
  • 现在它可以正确过滤日期,但会向下舍入到前一个日期。 2014-01-01T00:00:00.000Z 现在将变为 Dec 31, 2013
  • 你可以发布你正在尝试的表达方式
  • {{example.date | date:'longDate'}} 我认为这可能与T00:00:00.000Z 的时间有关。我现在正尝试在 rails 控制台中的所有记录中添加 1 秒

标签: javascript ruby-on-rails angularjs datetime coffeescript


【解决方案1】:

您可以使用指令ng-filter 来修改视图中的输出。 使用管道 | 过滤工作。

示例:

{{1288323623006 | date:'medium'}}: Oct 28, 2010 11:40:23 PM

在上面这个例子中

{{input | required_format }} = Formatted Output 

您可以通过以下链接了解许多日期格式选项。

https://docs.angularjs.org/api/ng/filter/date

【讨论】:

    【解决方案2】:

    只是想更新并让其他人检查这一点,我最终选择了一个我觉得更清洁的解决方案。

    我没有尝试更改视图中的数据,而是选择在我的模型中定义一个方法,然后通过该方法呈现 JSON。

    模型.rb:

        def format_date
          self.date.strftime("%B %d, %Y")
        end
    

    控制器.rb

        def index
          render json: Run.where(:date => 1.month.ago..Date.today).order(date: :asc).as_json(include: [:salmon, :dam], :methods => [:format_date])
        end
    

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      • 2021-11-18
      • 1970-01-01
      相关资源
      最近更新 更多