Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How might I move AngularJS Routes into separate file

I was curious if anybody was familiar with separating routes from the main app config function. My route list is getting quite large and I wanted to move them into a separate file and load them into the main config. I have seen this done before but I cannot remember or find where I saw it. Any help would be appreciated.

like image 856
Doug Kiser Avatar asked Jun 16 '14 20:06

Doug Kiser


People also ask

How does AngularJS routing work?

Routing in AngularJS is used when the user wants to navigate to different pages in an application but still wants it to be a single page application. AngularJS routes enable the user to create different URLs for different content in an application.

Why routing is not working in AngularJS?

The problem is the default hash-prefix used for $location hash-bang URLs is ('! ') that's why there are additional unwanted characters in your URL. If you actually want to have no hash-prefix and make your example work then you can remove default hash-prefix (the '!'

Which function is used to set up a default route in AngularJS?

Just use: $stateProvider . state("otherwise", { url : '/otherwise'...})


2 Answers

You can (and should !) use AngularJS modules to separate your application into modules.

Then, each module can define its own routes (with its own .config). Then, in your main module (usually "app"), you just need to require them as dependencies and you're set to go.

angular.module('blog', ['ngRoute'])
  .config(['$routeProvider', function ($routeProvider) {
    ...
  }];

angular.module('app', ['blog', 'user']);

Then you can have each module in its own file.

like image 195
Ven Avatar answered Oct 25 '22 22:10

Ven


You can put your config function in a separate file easily:

App-config.js

   angular.module('app').config(function(...){...});

Just make sure you include the module definition before you include App-config.js.

App-module.js

  angular.module('app',[...]).controller(...).etc
like image 34
pixelbits Avatar answered Oct 25 '22 21:10

pixelbits