简体   繁体   中英

Angular routing not working correctly

So I am attempting to try out Angular routing in my Ruby on Rails application.

The problem is that, when I land on a route, let's say '/' , and I have a angular routing that say's that when I land on it, it should load a template in my desired directory, then my Rails server will throw this error:

Started GET "/templates/index.html.erb" for 127.0.0.1 at 2014-12-02 18:03:39 +0200
ActionController::RoutingError (No route matches [GET] "/templates/index.html.erb"):

So basically it seems that it does not attempt to load my file from the folder but instead it tries to put the path that I told the angular route to the URL, and then make a request?

Because if I replace the templateUrl: with /users , which is an actual route in my app that responds with html, then It will effectily route to it. But that is not the behaviour I want.

I want Angular to replace the html template in my ng-view with the template specified when I enter the called route.

Here is my code for angular routing:

App = angular.module("App", ['ngRoute', 'growlNotifications'])

    App.config ($httpProvider) ->
        authToken = $("meta[name=\"csrf-token\"]").attr("content")
        $httpProvider.defaults.headers.common["X-CSRF-TOKEN"] = authToken

    App.config ($routeProvider, $locationProvider) ->
        $locationProvider.html5Mode true
        $routeProvider
            .when '/',
                templateUrl: 'templates/index.html.erb',
                controller: 'VisitorsCtrl'
            .when '/users',
                templateUrl: '../../views/users/index.html.erb',
                controller: 'UsersCtrl'
            .otherwise redirectTo: "/"

Also, in my application.html.erb I have set the base href to '/'

My template are located currently as so: app/assets/javascripts/angular/templates and my routing is defined in the angular folder

What could be the problem here?

  1. You want to get ERB templates, you probably want to change erb to only html
  2. Your templates are in wrong directory, for what you want you need to use correct path which si something like: "/assets/angular/templates/index.html" or put your templates into public directory "/public/templates"
  3. In case you want to still use ERB for rendering templates, you will need some solution with routing (config/routes.rb) this tempaltes to page controller bind on url: /templates/sth.html, but I guess it's quite ugly solution.
  4. I think the best solution for you is follow this great tutorial :) They store templates in public/templates directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM