How to integrate Rails views with angularjs ng-view?

前端 未结 2 1387
没有蜡笔的小新
没有蜡笔的小新 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
      
    0 讨论(0)
  • 2021-01-12 11:48

    Angular js provides its own routes. rails routes will always be used when you want to connect your views with database(CRUD). that is data binding with angular.js now i will show you how to use it with rails...

    I want to add new user using angular js views and list all users. i will use rails as backend to store users in database so i will create user_controller

    1. First Create resource of user. we will not create any views so be carefull for that

      rails g resource user name:string
      
    2. Then go to route.rb and check there is a route created, and create Home controller with index action that we will use as our single page application where our output will be yield.

      rails g controller home index
      root to: "home#index"
      
    3. type this command on terminal where you will see our 7 routes. we never use new and edit method, because new and edit don't respond to json.

      rake routes
      
    4. Now we want all user with a unique name so go to create_user migration and uncomment this line and then we will migrate the database.

      add_index :users, :name, unique: true
      rake db:migrate
      
    5. Now modify our controller so that all data fetching and insertion will be done with json format. so put this code inside users_controller.rb, if you are using rails 4 then follow this otherwise not. attributes will be adjustable in model.

      class UsersController < ApplicationController
        respond_to :json
      
        def index
          respond_with User.all
        end
      
        def create
          respond_with User.create(user_params)
        end
      
        private
          def user_params
            params.require(:user).permit(:name)
          end
      end
      

      Its time to use angulajs in our rails application

    6. Go to application.html.erb replace tag line with this

       <html ng-app="userApp">
      
    7. Now add angular.js file in asses/javascripts, download it from http://angularjs.org/

    8. Now we will create a controller to handle our angular application routes to know then that this controller wants something from me. so type this on terminal

      mkdir -p app/assets/javascripts/angular/controllers
      
    9. Now let's create the controller file itself. I'm calling this controller the "userCtrl", Thus our filename will be app/assets/javascripts/angular/controllers/userCtrl.js.coffee

    10. In controller userCtrl

      app = angular.module("userApp", ["ngResource"])
      
      @userCtrl = ($scope, $resource) ->
        User = $resource("/users", {id: "@id"}, {update: {method: "PUT"}})
        $scope.users = User.query()
      
        $scope.createUser = ->
          user = User.save($scope.newUser)
          $scope.users.push(user)
      

      (This will insert new user record into database, by creating createUser method)

    11. Create a view for taking input from user write this code in home/index.html.erb.

      <div ng-controller="userCtrl">
        <form ng-submit="createUser()">
          <label>Enter Name</label>
          <input type="text" placeholder="Enter user name" ng-model="newUser.name" />
          <button ng-click="createUser()" class="button tiny">Submit</button>
        </form>
      
      
        <!-- List all usres -->
        <h4 ng-show="users.$resolved && users.length > 1">All users</h4>
          <span ng-repeat="c in users">
            {{c.name}}<br>
          </span>
      </div>
      

    Run application and watch output.

    0 讨论(0)
提交回复
热议问题