Zohair Zaman
Zohair Zaman

Reputation: 59

Angular JS pre-populate form using url parameters

I have the following angular controller:

'use strict';
angular.module("generatorApp").controller('demogController',['$scope','$location','$http',function($scope, $location, $http){
        $scope.submit=function(){
        var feet=$scope.feet;
        var inches=$scope.inches;
        var isMale = false;

        if($scope.gender == 'male'){
            isMale = true; 
        }else{
            isMale = false;
        };

        var data = {
            emailId:$scope.emailId,
            gender:isMale,      
            heightCm: 2.54 *(this.feet * 12 + this.inches)      
        };

        localStorage.setItem('demogData', JSON.stringify(data));

    };  
}]);

Now here's the html:

<table>
<tr>
    <th> feet </th>
    <th> inches </th>
</tr>
<tr>
    <td><input type="number" ng-model="feet" placeholder="ft" name="feet" id="feet"></td>
    <td><input type="number" ng-model="inches" placeholder="in" name="inches" id="inches"><td>
</tr>   
</table>

And so on for email and some other entries. I am trying to pre-populate these table entries by using a url string of the following format:

https://blahblah.com/form?feet=x&inches=y 

So if the following string were entered, by forms would be populated already. Any suggestions would be appreciated.

Upvotes: 1

Views: 1512

Answers (1)

mcgraphix
mcgraphix

Reputation: 2733

You can get the query string params with:

$scope.feet = $location.search().feet; 

It is usually suggested that the models you use for your ng-model be properties of an object. For example:

$scope.formModel = {
    feet: $locaion.search().feet,
    inches: $location.search().inches
};

Then reference them this way:

<tr>
<td><input type="number" ng-model="formModel.feet" placeholder="ft" name="feet" id="feet"></td>
<td><input type="number" ng-model="formModel.inches" placeholder="in" name="inches" id="inches"><td>
</tr> 

Upvotes: 1

Related Questions