2012-12-14 59 views
6

我剛開始使用AngularJS與我的Rails應用程序,因爲我習慣於在Rails中使用haml模板我想在客戶端使用AngularJS做同樣的事情。問題是我不知道在haml文件中讀到哪裏。angularjs與客戶端哈姆

我有一個投資者的模型,我試圖將'show'模板轉換爲haml,因爲它是最簡單的開始。

這裏是我的AngularJS代碼與顯示

investors.js.coffee

# Setup the module & route 
    angular.module("investor", ['investorService']) 
    .config(['$routeProvider', ($provider) -> 
     $provider 
     .when('/investors/:investor_id', {templateUrl: '/investors/show.html', controller: 'InvestorCtrl'}) 
    ]) 
    .config(["$httpProvider", (provider) -> 
     provider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content') 
    ]) 

    angular.module('investorService', ['ngResource']) 
    .factory('Investor', ($resource) -> 
     return $resource('/investors/:investor_id.json', {}, { 
     show: {method: 'GET'}, 
     }) 
    ) 

    angular.bootstrap document, ['investor'] 

這裏是我的控制器AngularJS代碼

investors_controller.js.coffee

# Show Investor 
window.InvestorCtrl = ($scope, $routeParams, Investor) -> 
    html = haml.compileHaml({sourceId: 'simple'}) 
    $('#haml').html(html()) 

    investor_id = $routeParams.investor_id 
    $scope.investor = Investor.show({investor_id: investor_id}) 

在後端我有一個Rails JSON API。

這裏是show.html文件它讀取

<script type="text/haml-template" id="simple"> 
    %h1 {{investor.name}} 
</script> 

<div id="haml"></div> 

<h1>{{investor.name}}</h1> 

<p> 
    <b>Total Cost</b> 
    {{investor.total_cost}} 
</p> 

<p> 
    <b>Total Value</b> 
    {{investor.total_value}} 
</p> 

<a href='/investors/angular#/investors/{{investor.id}}/edit'>Edit</a> 
<a href='/investors'>Back</a> 

最後,我想有一個.haml並把它傳遞給templateURL並獲得haml_coffee_assets插件來編譯AngularJS開始盯着前動態字段和更改內容。

編號:https://github.com/netzpirat/haml_coffee_assets

目前,這會轉換HAML,放入股利與HAML的ID。但是,AngularJS不會將haml代碼中的{{investor.name}}更改爲投資者的名字,因爲它在操作中已經太晚了。

如何在這樣的AngularJS項目中正確實現客戶端哈姆模板?

+1

爲什麼不在服務器端haml渲染?照常編寫並提供haml,並讓客戶端應用程序請求轉換後的html。這樣你就可以利用haml的過濾器並且不會與角度作鬥爭。否則,在解析客戶端上的haml模板之後,您將手動引導您的角度應用程序。我沒有嘗試過,但它可以工作。 – jaime

+1

因此,如果我以haml格式使用Rails視圖,我會在templateUrl中放置什麼? – map7

回答

8

您可以將所有Haml模板放入assets/templates文件夾中。然後你鉤住你的資產管道使用該服務Haml的:

Rails.application.assets.register_engine '.haml', Tilt::HamlTemplate 

然後所有的模板將可以從/資產/(模板的名稱)。html的

如果你希望能夠包括在您Haml的模板,Rails的helper,你可以定義自定義模塊,並使用它:

module CustomHamlEngine 
    class HamlTemplate < Tilt::HamlTemplate 
    def evaluate(scope, locals, &block) 
     scope.class_eval do 
     include Rails.application.routes.url_helpers 
     include Rails.application.routes.mounted_helpers 
     include ActionView::Helpers 
     end 

    super 
    end 
    end 
end 

Rails.application.assets.register_engine '.haml', CustomHamlEngine::HamlTemplate 

這將增加所有鋼軌助手到範圍爲你的模板。然後,您可以將模板網址傳遞給角度,並且它會自動爲您做所有的腿部工作!

+0

我試圖完成同樣的事情(對不起,我知道這是一箇舊帖子)。我正在使用angular-rails-template和nghaml擴展;哈姆工作正常,但幫手不是。我將您的CustomHamlEngine添加到haml.rb初始化程序,但仍然沒有骰子。我在這裏發佈具體信息:http://stackoverflow.com/questions/22976912/rails-app-to-angular-haml-rails-helpers?lq=1 – Morgan