Ben L
Ben L

Reputation: 37

How do I set angular variable to value of query string?

My URL contains a query string, for example "www.website.php?feature1=true&feature2=false".

When my page loads, I want angular variables set to the value of the query string variables like this:

$scope.feature1 = $_POST['feature1'];
$scope.feature2 = $_POST['feature2'];

How can I do this? Thanks.

Upvotes: 0

Views: 737

Answers (2)

Nikolaj Dam Larsen
Nikolaj Dam Larsen

Reputation: 5694

Assuming your web entrypoint is a php page (or any other serverside rendered html page, such as a ASP.NET MVC View), the way I usually get values like these from the server into angular is using the constant function, and place it in the .php page right after you reference your angular app. Something like this:

<script src="app.js" />
<script>
    angular
        .module('app')
        .constant("myConfig", {
            "feature1": "<?php echo htmlspecialchars($_POST['feature1']); ?>",
            "feature2": "<?php echo htmlspecialchars($_POST['feature2']); ?>"
        });
</script>

Then in your controller, you just inject the constant: app.controller('Controller', ['myConfig', function(myConfig) {..}

While there are more convenient ways than this, when you're passing query strings (that can be accesses by JavaScript), with this approach you can pretty much pass in anything from server side code.

Upvotes: 0

leroydev
leroydev

Reputation: 2955

You can access GET parameters (URL parameters) through $routeParams:

app.controller('CtrlName', ['$scope','$routeParams', function($scope, $routeParams) {
  $scope.feature1 = $routeParams.feature1;
  $scope.feature2 = $routeParams.feature2;
}]);

Upvotes: 2

Related Questions