简体   繁体   中英

Reading URL from AngularJS

I had everything working flawlessly until I decided to implement apache, mod rewrite. There's 2 values, 2 parameters which information I need. I was using:

        $scope.scan_id = $location.search().scan_id;
        $scope.scan_domain = $location.search().scan_domain;

And, of course, it was working without any problem. As The previous URL was:

http://domainname.com/scanner/view_scan.html#?scan_id=10&scan_domain=clarin.com

So now, The current URL structure is:

http://domainname.com/scanner/view/scan/id/10/domain/clarin.com

I'm looking for a simple approach using $location service. I thought about something like a regex to look for scan/id/([0-9]){0,9999}/ and domain/(.)* but I certainly have no idea how to approach this in AngularJS.

Thanks in advance!

addendum:

In case it's not clear, I'm trying to get the values of the scan id and the domain name.

You can use the $location.path() to get the path of the URL ie

if the URL is http://example.com/#/some/path?foo=bar&baz=xoxo

you would get $location.path() --> /some/path

As you said there would be no params. First get the path and then split the URL accordingly.

For example, see the below:

 var myUrl = 'http://domainname.com/scanner/view/scan/id/10/domain/clarin.com', path = '/scanner/view/scan/id/10/domain/clarin.com', scanID, domainName, firstSplitStr, secondSplitStr; //path is what the $location.path() service would return you. firstSplitStr = '/scanner/view/scan/id/'; //as you already know the format secondSplitStr = '/domain/' scanID = path.replace(firstSplitStr, '').split(secondSplitStr)[0]; domainName = path.replace(firstSplitStr, '').split(secondSplitStr)[1]; console.log(scanID, domainName); 

I decided to make use of plain, vainilla JS, and regexes.

$scope.analizar_posicion = function() {

        //revisamos si los params no poseen información
        if (!$scope.scan_id || !$scope.scan_domain ) {

            //procesamos la dirección
            var address_now = $location.absUrl();

            //buscamos el scan id
            var scan_id_expresion = /scan\/id\/([0-9]{0,9})/i;
            var scan_id = address_now.match(scan_id_expresion);
            var scan_id = scan_id[1];
            console.log(scan_id);

            //buscamos el nombre de dominio
            var scan_domain_expresion = /domain\/((.){1,99})/i;
            var scan_domain = address_now.match(scan_domain_expresion);
            var scan_domain = scan_domain[1];
            console.log(scan_domain);

            //asociamos las variables al scope.
            $scope.scan_id = scan_id;
            $scope.scan_domain = scan_domain;

        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM