Angular 1 - 获取当前 URL 参数 [英] Angular 1 - get current URL parameters

查看:36
本文介绍了Angular 1 - 获取当前 URL 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从当前 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/surveys/2

我想提取的位:

app.dev/backend/:type/:id

app.dev/backend/ :type / :id

Angular 中有什么可以帮助我完成这项任务的吗?

Is there anything in Angular that could help me with this task ?

推荐答案

使用 ngRoute 从 URL 获取参数.这意味着您需要包含 angular-route.js 在您的应用程序中作为依赖项.有关如何在官方 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.

问题的解决方案:

// 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 ($routeParams) {
        console.log($routeParams.id, $routeParams.type);
    });

如果您没有启用 $locationProvider.html5Mode(true);.网址将使用 hashbang(/#/).

If you don't enable the $locationProvider.html5Mode(true);. Urls will use hashbang(/#/).

有关路由的更多信息可以在官方 angular $route API 文档.

More information about routing can be found on official angular $route API documentation.

旁注: 这个问题是回答如何使用 ng-Route 实现这一点,但我建议使用 ui-Router 用于路由.它更灵活,提供更多功能,文档很棒,被认为是 angular 的最佳路由库.

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.

这篇关于Angular 1 - 获取当前 URL 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆