简体   繁体   中英

Confused about angular and rails routing together

I'm trying to integrate AngularJS into part of my app where I have anything under the url /events/something be taken care of by angular routing. However, I've been following Angular's tutorial and this except I can't seem to get the view to render. I think I'm doing something wrong in my routing but I can't seem to figure it out. Can anyone help me out?

Sample link: http://localhost:3000/events/events1

Rails route:

get '/events/:id' => 'event#event'

Angular Code:

var app = angular.module('eventsApp', ['ngRoute', 'templates']);

app.config(['$routeProvider',
    function($routeProvider) {
        $routeProvider.when('events/:id', {
            templateUrl: 'eventTemp.html',
            controller: 'EventsCtrl'
        });
    }
]);
app.controller('EventsCtrl', function($scope, $http){
    console.log('yo!'); //this is never logging
});

outer template:

<div class = "event" ng-app="eventsApp">
    <div ng-view></div>
</div>

eventTemp.html

<h1>Text</h1>

I'm using the angular-rails-templates gem and I have all my templates in app/assets/javascripts/templates . This is what application.js looks like:

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require bootstrap-sprockets
//= require_tree .
//= require angular-rails-templates
//= require_tree ./templates
//= require turbolinks

I ran into a similar problem once, and the solution is this - use:

$routeProvider('/events/:id')

instead of

$routeProvider('events/:id')

Apparently, angular requires is routing paths to start with / .

Is your Angular app in the same directory as the template? If not, templateUrl needs to be the correct path.

templates/eventTemp.html

I played around with it and it turns out something is wrong with

$routeProvider.when('events/:id' 

When I change the method to this:

var app = angular.module('eventsApp', ['ngRoute', 'templates']);

app.config([
  '$routeProvider', function($routeProvider) {      
    $routeProvider.
     when('/', {
        templateUrl: '../templates/eventTemp2.html',
        controller: 'EventsCtrl2'
     }).
     otherwise({
        templateUrl: '../templates/eventTemp.html',
        controller: 'EventsCtrl'
     });
  }
]);
app.controller('EventsCtrl', function($scope, $http){
    console.log('yo!');
});

app.controller('EventsCtrl2', function($scope, $http) {
    console.log('yo2');
});

EventsCtrl2 and eventTemp.html2 get rendered.

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