Angularjs routing in different files

纵饮孤独 提交于 2019-12-03 01:42:57

问题


I'm checking out angular routing.

http://www.bennadel.com/blog/2420-Mapping-AngularJS-Routes-Onto-URL-Parameters-And-Client-Side-Events.htm

The examples I see have all the routes be defined in the same file. How do I have various routes be defined in different files / modules?


回答1:


In AngularJS routes are defined in configuration block. Each AngularJS module can have multiple configuration blocks and you can define routes in each and every configuration block. The final routing for the entire application is a sum of routes defined in all modules.

In practice you can do it like:

angular.module('myModule1', []).config(function($routeProvider){
  //define module-specific routes here
});

angular.module('myModule2', []).config(function($routeProvider){
  //define module-specific routes here
});

angular.module('myApp', ['myModule1', 'myModule2']).config(function($routeProvider){
  //define app-level routes here
});

Regarding the split over files - I guess this largely depends on how you split AngularJS modules in files. What I would recommend is sticking to one-file equals one-module principle.

You can see all this applied to a larger-scale web application in angular-app, an effort to build a reference for a non-trivial application written in AngularJS:

  • https://github.com/angular-app/angular-app

In the mentioned app you can see routes defined in multiple files, ex.:

  • https://github.com/angular-app/angular-app/blob/master/client/src/app/projectsinfo/projectsinfo.js
  • https://github.com/angular-app/angular-app/blob/master/client/src/app/projects/projects.js



回答2:


You can make the Angular application with different files without specifing them follow this steps

Step 1: Get the full url

var url = window.location.pathname;

Step 2 Sorting the filename alone

var filename = url.substring(url.lastIndexOf('/')+1);

Step 3 Displaying the result

alert(filename);

I have done this in w3schools try it editor http://www.w3schools.com/code/tryit.asp?filename=FDP3QTCP7V4E



来源:https://stackoverflow.com/questions/16260602/angularjs-routing-in-different-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!