21

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?

1 Answer 1

23

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();
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, that works. I made a mistake to give my angular app a name in het html tag, but didn't create the namespace.
One very minor improvement on the haml is to write %html{"ng-app" => true} or %html(ng-app=true), both of which will result in <html ng-app> without the empty string.
With haml 4.0.5 (under Rails 4) I've found that I can simply go %html(ng-app).
Side note: Another way to write an Angular directive in HAML -> %p{ng: {controller: "clock", repeat: "loop in loops"}} etc...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.