Reputation: 491
I'm learning angular, and have attached one to a rails api. I'm rendering an object's date in my view with angular {{example.date}}
. I'm assuming the best place to massage the JSON coming out of my rails api is in the angular controller, but having a hard time grasping how to do that. Here's my setup:
Rails controller:
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'
]
Angular Controller (coffeescript):
App.controller 'ExampleCtrl', ['$scope', 'Example', ($scope, Example) ->
$scope.example = Example.query()
]
All of this basic plumbing culminates to an ng-repeat
in my haml view:
%div{"ng-controller" => "ExampleCtrl"}
%ul
%li{"ng-repeat" => "example in example"}
%h3 {{example.date}}
I believe my Example.query()
in the angular controller is returning a large array of all the data. How would I write an each loop in coffeescript to transform all datetimes, such as Tue, 23 Sep 2014 00:00:00 UTC +00:00
, to formatted dates? I have bower hooked up on my app and can install moment js if that helps.
Thanks
Upvotes: 0
Views: 1287
Reputation: 491
Just wanted to update and let anyone else checking this out that I ended up going with a solution I feel is much cleaner.
Instead of trying to alter data in the view, I elected to define a method in my model, and then render the JSON through the method.
Model.rb:
def format_date
self.date.strftime("%B %d, %Y")
end
Controller.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
Hope that helps!
Upvotes: 0
Reputation: 2587
You can use directive ng-filter
to modify your outputs in the view.
Filter work using pipe |
.
Example:
{{1288323623006 | date:'medium'}}: Oct 28, 2010 11:40:23 PM
In this above example the
{{input | required_format }} = Formatted Output
You can go through below link for many formatting options for dates.
https://docs.angularjs.org/api/ng/filter/date
Upvotes: 4