问题描述
我想从目前的URL中提取数据,并在控制器中使用它。
例如,我有这个网址:
I want to extract data from current URL and use it in controller.For example I have this url:
app.dev/backend/surveys/2
这是我想提取位:
app.dev/backend/ :类型 / :ID
有没有角任何可以帮助我完成这个任务?
Is there anything in Angular that could help me with this task ?
推荐答案
要获得网址参数 ngRoute
。这意味着你将需要在您的应用程序一个依赖。更多信息,如何做到这一点官方。
To get parameters from URL with ngRoute
. It means that you will need to include angular-route.js in your application as a dependency. More information how to do this on official ngRoute documentation.
有关问题的解决方案是:
The solution for the question:
// You need to add 'ngRoute' as a dependency in your app
angular.module('ngApp', ['ngRoute'])
.config(function ($routeProvider, $locationProvider) {
// configure the routing rules here
$routeProvider.when('/backend/:type/:id', {
controller: 'PagesCtrl'
});
// enable HTML5mode to disable hashbang urls
$locationProvider.html5Mode(true);
})
.controller('PagesCtrl', function ($rootScope, $scope, $routeParams, $route) {
// If you want to use URL attributes before the website is loaded
$rootScope.$on('$routeChangeSuccess', function () {
console.log($routeParams.id);
console.log($routeParams.type)
});
});
如果您不启用 $ locationProvider.html5Mode(真);
。网址将使用hashbang( /#/
)。
If you don't enable the $locationProvider.html5Mode(true);
. Urls will use hashbang(/#/
).
有关路由的详细信息可以在官方的角度找到。
More information about routing can be found on official angular $route API documentation.
边注:的这个问题是回答如何实现这一目标采用NG-路线,但是我会建议使用的路由。它是更灵活,提供了更多的功能,本细则是伟大的,它被认为是角的最佳路由库。
Side note: This question is answering how to achieve this using ng-Route however I would recommend using the ui-Router for routing. It is more flexible, offers more functionality, the documentations is great and it is considered the best routing library for angular.
这篇关于AngularJS获取当前的URL参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!