How do I parse URL params after a hash with Angularjs?

后端 未结 4 1296
挽巷
挽巷 2020-12-29 06:36

I\'m trying to parse for the access_token from Foursquare where the URL is like this:

https://mywebsite.com/4sqredirect/#access_token=1234567890XXXXX

I\'ve t

相关标签:
4条回答
  • 2020-12-29 06:40

    I'm not aware of a "native angular" way to do it, but you do have access to the hash via location.hash as a string type. it's probably not ideal, but it's workable.

    0 讨论(0)
  • 2020-12-29 06:54

    From angular location service $location.hash() method return #after-hash

    so if your url is look like

    https://mywebsite.com/4sqredirect/#access_token=1234567890XXXXX
    

    then

    $location.hash() return access_token=1234567890XXXXX

    you need to split it split('=')[1]

    see this plunker when you click 4Square then $location.url() return

    /4sqredirect/#access_token=123456
    $location.hash().split('=')[1]
    

    return 123456

    0 讨论(0)
  • 2020-12-29 06:59

    Use $location.search()

    //e.g. url https://www.example.com/#!?name=123
    var s = $location.search();
    // {name: '123'}
    

    http://docs.angularjs.org/api/ng.$location

    Search:

    Returns search part (as object) of current url when called without any parameter.

    0 讨论(0)
  • 2020-12-29 07:05

    There is in fact no direct support from Angular JS to do this. I wouldn't use ngRoute, because it already might expect the # at a different place. A simple solution to your problem is to use the location.hash and the substring() function:

    <!DOCTYPE html>
    <html ng-app="app">
    
    <head>
    <script src="http://code.angularjs.org/1.2.6/angular.js"></script>
    <link href="style.css" rel="stylesheet" />
    <script>
    angular.module('app', [])
    .controller('AppCtrl', ['$scope', '$window', function($scope, $window) {
      $scope.accessToken = $window.location.hash.substring(14);
    }]);
    </script>
    </head>
    
    <body ng-controller="AppCtrl">
    <h1>Access Token</h1>
    <p>{{accessToken}}</p>
    </body>
    
    </html>
    
    0 讨论(0)
提交回复
热议问题