[英]angularjs with client side haml
我剛開始在我的Rails應用程序中使用AngularJS,因為我習慣在Rails中使用haml模板,我想在客戶端使用AngularJS。 問題是我不知道在haml文件中的哪個位置讀取。
我有一個投資者的模型,我正在嘗試將'show'模板轉換為haml,因為它是最容易開始的。
這是我關於show的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並將其放入id為haml的div中。 然而,AngularJS不會將haml代碼中的{{investor.name}}更改為投資者的名字,因為它在操作中為時已晚。
如何在AngularJS項目中正確實現客戶端haml模板?
您可以將所有Haml模板放在assets / templates文件夾中。 然后,您使用以下方法連接資產管道以服務Haml:
Rails.application.assets.register_engine '.haml', Tilt::HamlTemplate
然后,所有模板都可以從/ assets /(模板名稱).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
這會將所有rails助手添加到模板的范圍中。 然后你可以將模板URL傳遞給角度,它將自動為你完成所有腿部工作!
我的方法是使用$ templateCache將資產編譯時服務器端的所有haml渲染到'application.js'文件中。 結帳http://minhajuddin.com/2013/04/28/angularjs-templates-and-rails-with-eager-loading代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.