Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js with Sinatra

I would like to use Angular.js in my Sinatra applications. Unfortunately, I couldn't find any useful tips on this. I did find some Rails examples, however I have always found Rails and Padrino rather difficult to deal with, compared to the minimalistic philosophy of Sinatra.

I watched a number of videos (found by Googling angular.js), but am still finding it difficult to apply to Sinatra.

The most comprehensive tutorial I found so far was one from yearofmoo.com.

But still I am lost trying to apply this to Sinatra, and hacking my way out of this appears not to be an option as a simple error anywhere might set me off the right path anyway. I am lost and I admit it!!

Kindly any help based on your experience of trying to do something similar would be much appreciated, if shared. All I need at this point is to path my JSON from a Sinatra app to angular.js powered pages.

Thanks.

like image 983
zotherstupidguy Avatar asked Jan 24 '13 21:01

zotherstupidguy


1 Answers

As I stated in the comments above, the application structure would no longer rely on the server for templating the UI or generation of markup. Your server would essentially be a data and file host.

Okay.. presuming you have some route in Sinatra set up to return the following json (with content-type: application/json):

[
  { "id": 1, "name": "Foo" },
  { "id": 2, "name": "Bar" }
]

You would then use something like this in Angular to load that data (basically):

app.js

//create your application module.
var app = angular.module('myApp', []);

//add a controller to it
app.controller('MyCtrl', function($scope, $http) {

   //a scope function to load the data.
   $scope.loadData = function () {
      $http.get('/Your/Sinatra/Route').success(function(data) {
         $scope.items = data;
      });
   };

});

Then in your markup you'd do this:

<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MyCtrl">
    <button ng-click="loadData()">Load Data From Server</button>
    <ul>
         <li ng-repeat="item in items">ID: {{item.id}}, Name: {{item.name}}</li>
    </ul>
  </body>

</html>

I hope that helps.

like image 65
Ben Lesh Avatar answered Oct 04 '22 10:10

Ben Lesh