与客户端haml的angularjs
我刚刚开始在我的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('https://stackoverflow.com/investors/:investor_id', {templateUrl: 'https://stackoverflow.com/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('https://stackoverflow.com/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文件
%h1 {{investor.name}} {{investor.name}}
Total Cost {{investor.total_cost}}
Total Value {{investor.total_value}}
Edit Back
最后我希望有一个.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代码。
- 如何从运行在不同端口上的本地AngularJS应用程序向本地Rails应用程序发出请求?
- 无法从Rails API获取JSON数据
- angular-rails-templates:找不到模板
- 确保用户使用cookieStore和AngularJS登录或注销的最佳实践
- 如何在纯Javascript HTML Web App中隐藏凭据
- Access-Control-Allow-Origin不允许使用Rails 3和Angularjs Origin http:// localhost。
- Javascript错误未知提供者:在Rails缩小Angularjs之后的tProvider < – t
- 这对于sinatra + angular.js +自定义提供程序的Oauth2工作流的概念是否正确?
- 将Angularjs和Rails应用程序分离为独立组件