Javascript 如何使用AngularJS获取url参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11758079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:59:50  来源:igfitidea点击:

How to get the url parameters using AngularJS

javascriptangularjsrouteparams

提问by praveenpds

HTML source code

HTML源代码

<div ng-app="">
    <div ng-controller="test">
      <div ng-address-bar browser="html5"></div>
      <br><br>
      $location.url() = {{$location.url()}}<br>
      $location.search() = {{$location.search('keyword')}}<br>
      $location.hash() = {{$location.hash()}}<br>     
      keyword valus is={{loc}} and ={{loc1}}
  </div>
</div>

AngularJS source code

AngularJS 源代码

<script>
function test($scope, $location) {
  $scope.$location = $location;
  $scope.ur = $scope.$location.url('www.html.com/x.html?keyword=test#/x/u');
  $scope.loc1 = $scope.$location.search().keyword ;    
    if($location.url().indexOf('keyword') > -1){    
        $scope.loc= $location.url().split('=')[1];
        $scope.loc = $scope.loc.split("#")[0]        
    }
  }
 </script>

Here the variables locand loc1both return testas the result for the above URL. Is this the correct way?

这里的变量locloc1两者都返回test作为上述 URL 的结果。这是正确的方法吗?

回答by Jeff

I know this is an old question, but it took me some time to sort this out given the sparse Angular documentation. The RouteProviderand routeParamsis the way to go. The route wires up the URL to your Controller/View and the routeParams can be passed into the controller.

我知道这是一个老问题,但考虑到稀疏的 Angular 文档,我花了一些时间来解决这个问题。该RouteProviderrouteParams是要走的路。路由将 URL 连接到您的控制器/视图,并且可以将 routeParams 传递到控制器中。

Check out the Angular seedproject. Within the app.js you'll find an example for the route provider. To use params simply append them like this:

查看Angular 种子项目。在 app.js 中,您将找到路由提供程序的示例。要使用参数,只需像这样附加它们:

$routeProvider.when('/view1/:param1/:param2', {
    templateUrl: 'partials/partial1.html',    
    controller: 'MyCtrl1'
});

Then in your controller inject $routeParams:

然后在您的控制器中注入 $routeParams:

.controller('MyCtrl1', ['$scope','$routeParams', function($scope, $routeParams) {
  var param1 = $routeParams.param1;
  var param2 = $routeParams.param2;
  ...
}]);

With this approach you can use params with a url such as: "http://www.example.com/view1/param1/param2"

通过这种方法,您可以使用带有 url 的参数,例如:“ http://www.example.com/view1/param1/param2

回答by Javarome

While routing is indeed a good solution for application-level URL parsing, you may want to use the more low-level $locationservice, as injected in your own service or controller:

虽然路由确实是应用程序级 URL 解析的一个很好的解决方案,但您可能希望使用更底层的$location服务,如在您自己的服务或控制器中注入的:

var paramValue = $location.search().myParam; 

This simple syntax will work for http://example.com/path?myParam=paramValue. However, only if you configured the $locationProviderin the HTML 5 mode before:

这种简单的语法适用于http://example.com/path?myParam=paramValue. 但是,仅当您$locationProvider之前在 HTML 5 模式中配置了:

$locationProvider.html5Mode(true);

Otherwise have a look at the http://example.com/#!/path?myParam=someValue"Hashbang" syntax which is a bit more complicated, but have the benefit of working on old browsers (non-HTML 5 compatible) as well.

否则看看http://example.com/#!/path?myParam=someValue"Hashbang" 语法有点复杂,但有在旧浏览器(非 HTML 5 兼容)上工作的好处好。

回答by jlents

If you're using ngRoute, you can inject $routeParamsinto your controller

如果你使用 ngRoute,你可以注入$routeParams你的控制器

http://docs.angularjs.org/api/ngRoute/service/$routeParams

http://docs.angularjs.org/api/ngRoute/service/$routeParams

If you're using angular-ui-router, you can inject $stateParams

如果您使用的是 angular-ui-router,则可以注入 $stateParams

https://github.com/angular-ui/ui-router/wiki/URL-Routing

https://github.com/angular-ui/ui-router/wiki/URL-Routing

回答by Mekha Lomlao

I found solution how to use $location.search() to get parameter from URL

我找到了如何使用 $location.search() 从 URL 获取参数的解决方案

first in URL u need put syntax " # " before parameter like this example

首先在 URL 你需要像这个例子一样在参数之前放置语法“#”

"http://www.example.com/page#?key=value"

"http://www.example.com/page#?key=value"

and then in your controller u put $location in function and use $location.search() to get URL parameter for

然后在你的控制器中你把 $location 放在函数中并使用 $location.search() 来获取 URL 参数

.controller('yourController', ['$scope', function($scope, $location) {

     var param1 = $location.search().param1; //Get parameter from URL

}]);

回答by ak1

If the answers already posted didn't help, one can try with $location.search().myParam; with URLs http://example.domain#?myParam=paramValue

如果已经发布的答案没有帮助,可以尝试使用 $location.search().myParam; 使用 URL http://example.domain#?myParam=paramValue

回答by Russell Hankins

function GetURLParameter(parameter) {
        var url;
        var search;
        var parsed;
        var count;
        var loop;
        var searchPhrase;
        url = window.location.href;
        search = url.indexOf("?");
        if (search < 0) {
            return "";
        }
        searchPhrase = parameter + "=";
        parsed = url.substr(search+1).split("&");
        count = parsed.length;
        for(loop=0;loop<count;loop++) {
            if (parsed[loop].substr(0,searchPhrase.length)==searchPhrase) {
                return decodeURI(parsed[loop].substr(searchPhrase.length));
            }
        }
        return "";
    }

回答by Antonio

When using angularjs with express

使用带有 express 的 angularjs 时

On my example I was using angularjs with express doing the routing so using $routeParams would mess up with my routing. I used the following code to get what I was expecting:

在我的示例中,我使用 angularjs 和 express 进行路由,因此使用 $routeParams 会弄乱我的路由。我使用以下代码来获得我所期望的:

const getParameters = (temp, path) => {
  const parameters = {};
  const tempParts = temp.split('/');
  const pathParts = path.split('/');
  for (let i = 0; i < tempParts.length; i++) {
    const element = tempParts[i];
    if(element.startsWith(':')) {
      const key = element.substring(1,element.length);
      parameters[key] = pathParts[i];
    }
  }
  return parameters;
};

This receives a URL template and the path of the given location. The I just call it with:

这将接收一个 URL 模板和给定位置的路径。我只是这样称呼它:

const params = getParameters('/:table/:id/visit/:place_id/on/:interval/something', $location.path()); 

Putting it all together my controller is:

把它们放在一起我的控制器是:

.controller('TestController', ['$scope', function($scope, $window) {
  const getParameters = (temp, path) => {
    const parameters = {};
    const tempParts = temp.split('/');
    const pathParts = path.split('/');
    for (let i = 0; i < tempParts.length; i++) {
      const element = tempParts[i];
      if(element.startsWith(':')) {
        const key = element.substring(1,element.length);
        parameters[key] = pathParts[i];
      }
    }
    return parameters;
  };

const params = getParameters('/:table/:id/visit/:place_id/on/:interval/something', $window.location.pathname);
}]);

The result will be:

结果将是:

{ table: "users", id: "1", place_id: "43", interval: "week" }

Hope this helps someone out there!

希望这可以帮助那里的人!

回答by Rohit Parte

Simple and easist way to get url value

获取url值的简单方法

First add # to url (e:g -  test.html#key=value)

url in browser (https://stackover.....king-angularjs-1-5#?brand=stackoverflow)

var url = window.location.href 

(output: url = "https://stackover.....king-angularjs-1-5#?brand=stackoverflow")

url.split('=').pop()
output "stackoverflow"