user1542639
user1542639

Reputation: 597

Angularjs in rails: Change page without reloading?

What is the best practice of changing pages in rails by using angularjs such that there will be no refresh? (I will use fadein animation on the switched page).

In addition to that, If I want to keep database query logic within Angularjs, so is there a way to read Rails url argument (foo.com/:arg) for Angularjs?

Upvotes: 0

Views: 512

Answers (1)

ksimons
ksimons

Reputation: 3826

If you're working with an existing Rails application which you want to convert to Angular, you'll likely not get to keep a lot of the templating/view code from Rails. Instead, start clean by keeping your server-side APIs and statically serve up your Angular application. If you're starting with a clean rails app, keep in mind that it will basically be Rails' job to provide a JSON/XML API and to statically serve up the Angular app.

To change views in Angular without reloading the page, you'll want to use $routeProvider in coordination with ng-view. Register each of the routes in your application with their corresponding view template:

angular.module('user-manager', [])
    .config(function($routeProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'views/main.html'
            })
            .when('/user/:id', {
                templateUrl: 'views/user.html',
                controller: 'UserCtrl'
            })
            .otherwise({
                redirectTo: '/'
           });
});

And then declare the ng-view somewhere in your main index.html:

<body ng-app="user-manager">

    <!-- Main view -->
    <div ng-view></div>
</body>

The ng-view will get replaced with the relevant template from your routes. For more details and a more complete example, see: http://docs.angularjs.org/api/ngRoute.$route

Upvotes: 1

Related Questions