在Angular控制器中将rails日期时间更改为字符串



我正在学习angular,并已将其附加到rails api。我用角度{{example.date}}在视图中呈现对象的日期。我假设处理rails-api中的JSON的最佳位置是在角度控制器中,但很难掌握如何做到这一点。这是我的设置:

轨道控制器:

class ExampleController < ApplicationController
    def index
      render json: Example.all
    end
    def show
      render json: Example.find(params[:id])
    end
end

Angular Service(coffeescript):

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

角度控制器(coffeescript):

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

在我看来,所有这些基本的管道都达到了ng-repeat的顶点:

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

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

感谢

您可以使用指令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

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

我没有试图更改视图中的数据,而是选择在模型中定义一个方法,然后通过该方法呈现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

希望能有所帮助!

最新更新