Using AngularJS within Haml views of a Rails app

John picture John · Apr 9, 2013 · Viewed 16.4k times · Source

I have a Rails app with Haml views. Now I want to add AngularJS to some parts of the application, but the problem is that the Haml views are rendered server-side and the AngularJS code is not working, because it is rendered client-side.

Let's say I have just this in my index.html.haml:

!!!
%html{"ng-app" => "Test"}
  %head
    %script{:src => "http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.js"}
    :javascript
      function Clock($scope) {
        $scope.currentTime = new Date();
      }
    %title Welcome to AngularJS
  %body
    %h1 Hello, World.
    %p{"ng-controller" => "Clock"}
      The current time is {{currentTime | date:'h:mm:ss a'}}.

So currently, it's just printing out everything within the curly brackets without actually processing it. There are solutions but they for situations where your complete view is replaced by an AngularJS template. I want to use AngularJS mainly for small bits of functionality in my Rails app. Any ideas how to solve this?

Answer

Leon picture Leon · Apr 9, 2013

John,

I have edited your code a bit here: http://codepen.io/anon/pen/vKiwH

%html{"ng-app"=>true}
 %p{"ng-controller" => "clock"}
  The current time is {{currentTime | date:'h:mm:ss a'}}.

and the javascript is:

function clock($scope) {
  $scope.currentTime = new Date().getTime();
}