Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 1.5 routing example

I am trying to locate an angular 1.5 routing example using $route. The JSFiddle examples I've looked at break if I use higher angular version than used to create the code example. I can't find anything working above 1.2. Ideally I need a working example for AngularJS 1.5.

I have already tried this example:

var app = angular.module( "myApp", [] );

app.config( function ( $routeProvider ) {
  $routeProvider
  .when( '/this', { templateUrl: 'this.html' } )
  .when( '/that', { templateUrl: 'that.html' } )
  .when( '/other', { templateUrl: 'other.html' } )
  .otherwise( { redirectTo: '/this' } );
});

app.controller( 'MainCtrl', function ( $scope ) {
});

Which fails for 1.2 (and presumably above).

like image 606
Laurence Fass Avatar asked Oct 21 '15 10:10

Laurence Fass


1 Answers

When AngularJS 1.2 was released ngRoute has been moved into its own module. This means you need to include a seperate file to get routing to work above and equal AngularJS 1.2. This means the first thing to do is to include angular-route.js file, just as you would include any other script

<script src="angular-route.js">

Second, have include the dependency to your app module.

var myApp = angular.module('myApp', ['ngRoute', 'otherModule']);

Last, you can configure your $routeProvider as you did in your code above:

app.config(function($routeProvider){
    $routeProvider
      .when('/',{
          template: '<h1>Work</h1><a href="#/test">Test Route</a>'
      })
      .when('/test',{
          template: '<h1>Test</h1><a href="#/">Back</a>'
      })
      .otherwise({ 
        template: '<h1>Not Found</h1>'
      });
});

That's the whole setup magic behind the routing. Here is a working example.

Edit 1:

If you are using bower you can get the module with the following:

bower install angular-route
like image 171
LordTribual Avatar answered Sep 19 '22 12:09

LordTribual