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

查看:236
本文介绍了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/ :输入 / :id

Angular中是否有任何可以提供帮助的内容我有这个任务吗?

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

推荐答案

从URL获取参数 ngRoute 。这意味着您需要包含 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(/#/).

有关路由的更多信息,请参阅官方角度 $ route API文档

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

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

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天全站免登陆