Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Rails ID to Angular

I have a Rails 3.2 app, where Angular code is calling a Rails route. I need to pass the route the (Rails) id of the page, and am having some difficulty. I have embedded the id onto the page using a hidden div, but cannot access it from Angular, in order to pass back into Rails.

I've reviewed this blogpost: http://spin.atomicobject.com/2013/11/22/pass-rails-data-angularjs/

Here is a similar question:

Rails route params in angular

I seem to be getting something but it is an object, not the id I need. A button is pressed which triggers the Angular call. An example url on the page would be, in which case I am trying to pass 833:

http://0.0.0.0:3000/batches/833/edit

worksheet.js.coffee

@WorksheetCtrl = ($scope) ->
  .
  .
$scope.exportCSV = ->
  batchId = angular.element(document.querySelector("#data-batch-id"))
  location.href = "/wizards/#{batchId}/worksheet_export.csv?#{Object.toQueryString($scope.getPostParams())}"

config/routes.rb

match 'wizards/:id/worksheet_export', :to => 'wizards#worksheet_export', :as => 'worksheet_export'

app/views/batches/edit.html.erb

<div ng-controller="WorksheetCtrl" ng-init="init()">
   <div id="div-passed-data" data-batch-id="<%= @batch.id %>"></div>

app/controllers/wizards_controller.rb

def worksheet_export
  Rails.logger.debug "id: #{params[:id]}"
  Rails.logger.debug "params: #{params}"
  .
  .

Rails Console

Started GET "/wizards/[object%20Object]/worksheet_export.csv" for 127.0.0.1 at 2014-01-12 21:52:31 +0100
Processing by WizardsController#worksheet_export as CSV
  Parameters: {"id"=>"[object Object]"}
id: [object Object]
params: {"controller"=>"wizards", "action"=>"worksheet_export", "id"=>"[object Object]", "format"=>"csv"}
like image 332
port5432 Avatar asked Mar 09 '26 21:03

port5432


1 Answers

SOLVED -- better solutions welcome

It seems rather convoluted, but I managed to pass in the id via the init() method and from there added it to the $scope.

app/views/batches/edit.html.erb

<div ng-controller="WorksheetCtrl" ng-init="init(<%= @batch.id %>)">

worksheet.js.coffee

$scope.init = (batch_id)->
  console.log("batch: #{batch_id}")
    $(document).ready ->
      $('#editCriteriasModal').on 'hidden', ->
        $scope.$apply ->
          $scope.criteriaListValidation $scope.modalCriteriaList
          $scope.search()
      $scope.batchId = batch_id 
.
.
$scope.exportCSV = ->
    location.href = "/wizards/#{$scope.batchId}/worksheet_export.csv?#{Object.toQueryString($scope.getPostParams())}"
like image 127
port5432 Avatar answered Mar 12 '26 09:03

port5432



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!