nayan chowdhury
nayan chowdhury

Reputation: 283

$location is not working on angular?

i am just trying to use angulat location but dont know wh it is not working =>

app.controller("maintainenceCtrl", function ($scope, $window, $sessionStorage, ArbreeService, $location) {
     angular.element(document).ready(function () {
            var absUrl = $location.search();
            console.log(absUrl);
        });});

and my url==> http://localhost:49696/Team/Maintenance?selectionCriteria=bulkinvite

but dont know why not working ==> returning a null object==>console....

Upvotes: 1

Views: 113

Answers (1)

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38663

Make sure you enable

$locationProvider.html5Mode(true); 

Then try this below way. this is the 100% correct way to get query string value from URL

 var search= $location.search();
 if(search !=null)
 {
   var objectValue = search.selectionCriteria
 }

Update1

is there any way to get just parameter values not using angular route or ui route?

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var queryValue = getParameterByName('selectionCriteria');

referred from : Getting values from query string in an url using AngularJS $location

Update 2

And you can use $routeParams

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.

The solution for the question:

// 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);
    });

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

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


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.

Upvotes: 1

Related Questions