0

How can I get parameter from the current URL ?

I have URL http://localhost/admin.brands/edit?brandid=1&brandname=samsung&isactive=1. For instance, how can I get brandid from the URL ?

I will modify this:

<script>

var app = angular.module('myApp', [])
    .controller("PostsCtrl", function($scope, $http) {
      $http.get('http://localhost/admin.brands/getJsonBrandAndEdit?brandid=XX').
        success(function(data, status, headers, config) {
          $scope.post = data;

        }).
        error(function(data, status, headers, config) {

        });
    });
</script>
6
  • you mean getting it in angular or in your server? which language. In angular you can straight away edit the string. Commented May 26, 2015 at 8:36
  • I want to get it in angular. Commented May 26, 2015 at 8:37
  • 1
    You could use angular routes, it would make your code cleaner. Commented May 26, 2015 at 8:38
  • 1
    I don't get it, why do you need this brandid. If you use $http.get('url') you have to put parameter in this url and this will return a result. Commented May 26, 2015 at 8:38
  • 1
    Sorry, I've edited the question. Commented May 26, 2015 at 8:40

1 Answer 1

3

You should probably be using angular router or ui router (Would recommend the later one) and pass these values which are currently being passed in the query param in the route, would be much easier to read the values then from your controller.

Would have been something like this

.controller('PostsCtrl',
    [       '$scope','$stateParams'
    function($scope , $stateParams ) {    
        // 
        $scope.brandId= $stateParams.brandid;
        ...

Incase you dont want to do it and need a quick fix, here is something that would work...

JavaScript:

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, " "));
}

Usage:

var brandId = getParameterByName('brandid');

Source : How can I get query string values in JavaScript?

Sign up to request clarification or add additional context in comments.

2 Comments

I am new at angular. Can you complete angular controller, please ?
Just use your code ( $http.get ......) in your controller , you can access at parameter with $stateParams. Like this : $stateParams.brandid

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.