在Rails应用程序的Haml视图中使用AngularJS

Joh*_*ohn 21 haml ruby-on-rails-3 angularjs

我有一个带有Haml视图的Rails应用程序.现在我想将AngularJS添加到应用程序的某些部分,但问题是Haml视图是在服务器端呈现的,而AngularJS代码不起作用,因为它呈现在客户端.

假设我在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'}}.
Run Code Online (Sandbox Code Playgroud)

所以目前,它只是打印大括号内的所有内容而不实际处理它.有解决方案,但它们适用于您的完整视图被AngularJS模板替换的情况.我想在我的Rails应用程序中使用AngularJS主要用于少量功能.任何想法如何解决这个问题?

Leo*_*eon 23

约翰,

我在这里编辑了你的代码:http://codepen.io/anon/pen/vKiwH

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

而javascript是:

function clock($scope) {
  $scope.currentTime = new Date().getTime();
}
Run Code Online (Sandbox Code Playgroud)

  • 对haml的一个非常小的改进是编写%html {"ng-app"=> true}或%html(ng-app = true),两者都会导致<html ng-app>而没有空字符串. (8认同)