【问题标题】:Using AngularJS within Haml views of a Rails app在 Rails 应用程序的 Haml 视图中使用 AngularJS
【发布时间】:2013-03-31 12:08:38
【问题描述】:

我有一个带有 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'}}.

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

【问题讨论】:

    标签: ruby-on-rails-3 angularjs haml


    【解决方案1】:

    约翰,

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

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

    而 javascript 是:

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

    【讨论】:

    • 谢谢,这行得通。我错误地在 het html 标记中为我的 Angular 应用程序命名,但没有创建命名空间。
    • 对haml的一个非常小的改进是写了%html{"ng-app" => true}或者%html(ng-app=true),这两个都会导致 没有空字符串。
    • 使用haml 4.0.5(在Rails 4下)我发现我可以简单地使用%html(ng-app)
    • 旁注:在 HAML 中编写 Angular 指令的另一种方法 -> %p{ng: {controller: "clock", repeat: "loop in loops"}} 等...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    • 2012-01-26
    • 2017-10-18
    • 2011-07-07
    • 2023-03-22
    相关资源
    最近更新 更多