StudioTime
StudioTime

Reputation: 23959

Reading URL Query string

I have the following URL:

http://myUrl.com/#/chooseStyle?imgUpload=6_1405794123.jpg

I want to read the imgUpload value in the query string - I'm trying:

alert($location.search().imgUpload);

But nothing alerts, not even a blank alert - but console reads:

$location is not defined

I need this value to add into a controller to pull back data, and also to carry into the view itself as part of a ng-src

Is there anything I'm doing wrong? this is my app config:

capApp.config(function($locationProvider, $routeProvider) {
  $locationProvider.html5Mode(false);
  $routeProvider

  // route for the home page
  .when('/', {
    templateUrl : '/views/home.html',
    controller  : 'mainController'
  })

  // route for the caption it page
  .when('/capIt', {
    templateUrl : '/views/capIt.html',
    controller  : 'mainController'
  });
}):

This is the view:

<div class="container text-center">
  <h1 class="whiteTextShadow text-center top70">Choose your photo</h1>
</div>

<script>
  alert($location.search().imgUpload);
</script>

Main controller:

capApp.controller('mainController', function($scope) {
  $scope.message = 'Whoop it works!';
});

My end goal is that I can find a solution to capturing and re-using data from the query string.

I will also mention, this is only my first week in Angular, loving it so far! A lot to learn...

Upvotes: 0

Views: 103

Answers (2)

Nielarshi
Nielarshi

Reputation: 1136

You should not do this
<script>
  alert($location.search().imgUpload);
</script>

// you need to inject the module $location 
//(either in service, or controller or wherever you want to use it)
// if you want to use their APIs

capApp.controller('mainController', function($scope, $location) {
  $scope.message = 'Whoop it works!';
  //use API of $location
  alert($location.search().imgUpload);
});

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691635

<script>
  alert($location.search().imgUpload);
</script>

You're making two mistakes here:

  1. executing code while the page is loading, and the angular application is thus not started yet
  2. assuming $location is a global variable. It's not. It's an angular service that must be injected into your controller (or any other angular component). This should cause an exception to be thrown and displayed in your console. Leave your console open always, and don't ignore exception being thrown.

Upvotes: 1

Related Questions