How to integrate Rails views with angularjs ng-view?

前端 未结 2 1405
没有蜡笔的小新
没有蜡笔的小新 2021-01-12 10:59

I have created rails view (ERB). However, I want to integrate it into angularjs $routeProvider, but I don\'t know what url should I fill into templateUrl<

2条回答
  •  温柔的废话
    2021-01-12 11:34

    In this page, it gives a 'Hello World' example of scaffolding Angularjs + Rails. (Please ignore the extra parts for additional functions.) When you type any name,then get a Hello message displayed for him, you've got a functional Angularjs + rails app.

    A couple of points to share:

    • A simple way to include angular.js file:

      1. Put gem 'angularjs-rails' in your Gemfile;

      2. Then put //= require angular in your app/assets/javascripts/application.js file.

      3. Very likely you will need //= require angular-resource so that you can use ngResource services to access the RESTful API provided by rails applicaiton from server end. See this page for examples.

    • Include Rails-controller-specific javascript codes in layout this way:

      1. Add the following codes to app/views/layouts/applications.html.erb file after the line <%= yield %>:

        <%= page_specific_js = "#{params[:controller]}_#{params[:action]}" %>
        <%= javascript_include_tag page_specific_js if Rails.application.assets.find_asset page_specific_js %>
        <%= stylesheet_link_tag  page_specific_js if Rails.application.assets.find_asset page_specific_js %>
        
      2. Remove //= require_tree . from application.js.

    • Include the following codes in config/initializers/assets.rb for precompiling js and css files:

      Rails.application.config.assets.precompile << Proc.new do |path|
        if path =~ /\.(css|js)\z/
          full_path = Rails.application.assets.resolve(path).to_path
          app_assets_path = Rails.root.join('app', 'assets').to_path
          if full_path.starts_with? app_assets_path
            puts "including asset: " + full_path
            true
          else
            puts "excluding asset: " + full_path
            false
          end
        else
          false
        end
      end
      

提交回复
热议问题