简体   繁体   中英

Select Option in AngularJS returning object not value

I'm still learning AngularJS, so im not quite sure as to the best way to implement this; I'd be fine with doing this in ordinary HTML, but wasn't able to use the "selected" property, so i switched to an Angular element - which im new to using.

I have a form, with a Drop down box, where the user selects either "User" or "Administrator". A User has the value of "2", where Administrator has the value of "1".
By default, 'User' is the pre-selected item in the list.
My problem is, when the form is being submitted (via AJAX) to PHP, the form is submitting an Object like {value : "2", name : "User"} where i want it to just submit the value, ie: "2".

HTML code:

<div class="form-group col-md-6">
    <label for="usrlevel">User Level:</label>
    <select class="form-control form-control-sm"
            data-ng-init="formData.usrlevel = usrlevels[0]"
            data-ng-model="formData.usrlevel"
            data-ng-options="x.name for x in usrlevels">
    </select>
</div>

Javascript Code:

app.controller("admController", function ($scope, $http, $location) {
    $scope.usrlevels = [
      {value : "2", name : "User"},
      {value : "1", name : "Administrator"}
    ];

    $scope.addForm = function() {
        var ans="";
        $http({
            method  : 'POST',
            url     : 'php/addstaff.php',
            data        : $.param($scope.formData),
            headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  //set the headers so angular passing info as form data (not request payload)
            }).then(function (response) {
                console.log(response.data);
                ans = response.data;
                if (!ans.success) {
                    // Add Error handling

                } else {
                    $('#addModal').modal('hide');
                    $scope.getStaff();  //refreshes table display
                }
            }).catch(function(response){
                console.log(response.data);
            });
    };

And here's an image of the debugger, showing that for 'usrlevel' the form is submitting an object, when it should just be submitting the value of the selected item.
Thus, in the debugger, it should just be showing usrlevel:"2" 在此处输入图片说明

UPDATE: As people seem to be under the impression that only the userlevel should be submitted by the AJAX call (I thought the debugger window image would make it clear that the userlevel is 1 element in the form) here's the actual HTML form.

<form data-ng-submit="addForm()" name="addform" method="POST">
    <div class="form-group">
        <label for="name">Full Name:</label>
        <input type="text" class="form-control form-control-sm" name="name" data-ng-model="formData.name" id="name" placeholder="">
    </div>
    <div class="form-group">
        <label for="address">Address:</label>
        <input type="text" class="form-control form-control-sm" name="address" data-ng-model="formData.address" id="address" placeholder="">
    </div>
    <div class="form-group">
        <label for="suburb">Suburb:</label>
        <input type="text" class="form-control form-control-sm" name="suburb" data-ng-model="formData.suburb" id="suburb" placeholder="">
    </div>
    <div class="form-group">
        <label for="phone">Phone:</label>
        <input type="tel" class="form-control form-control-sm" name="phone" data-ng-model="formData.phone" id="phone" placeholder="">
        </div>
    <div class="form-row">
    <div class="form-group col-md-6">
        <label for="postcode">Post Code:</label>
        <input type="text" class="form-control form-control-sm" name="postcode" data-ng-model="formData.postcode" id="postcode" placeholder="">
    </div>
    <div class="form-group col-md-6">
        <label for="usrlevel">User Level:</label>
        <select class="form-control form-control-sm" data-ng-init="formData.usrlevel = usrlevels[0]" data-ng-model="formData.usrlevel" data-ng-options="x.name for x in usrlevels"></select>
    </div>
</div>
<div class="form-group">
    <label for="email">Email:</label>
    <input type="email" class="form-control form-control-sm" name="email" data-ng-model="formData.email" id="email" placeholder="">
</div>
<div class="form-group">
    <label for="suburb">Password:</label>
    <input type="password" class="form-control form-control-sm" name="password" data-ng-model="formData.password" id="password" placeholder="">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" value="Reset" class="btn btn-secondry">Clear</button>

You are asking why u get whole object on select and not only value selected.

This is because you used

 data-ng-options="x.name for x in usrlevels"

Which will set X to model on select, if you want only name/any other attr of x to be set to model you need to use

  data-ng-options="x.value as x.name for x in usrlevels" data-ng-model="formData.value"

As tell angular select x show it as y.

to make default selection work

now you need to update $score.formData.value with value of selected user object.

so forexample in ur controller

app.controller("admController", function ($scope, $http, $location) {
    $scope.usrlevels = [
      {value : "2", name : "User"},
      {value : "1", name : "Administrator"}
    ];
    $scope.formData = { value: "1"} // prepare formData and set user with value 1 (Admin) to be selected by default

finally send whole formData.

http({
        method  : 'POST',
        url     : 'php/addstaff.php',
        data        : $scope.formData,
        headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  //set the headers so angular passing info as form data (not request payload)
        }).then(function (response) {
            ...etc

Again pass only wt u need to data of ajax, dont pass whole object!

Problem is with your model. Well, an easy to understand syntax would look like this

 angular.module("app",[]).controller('ctrl', function($scope){ $scope.users= [{value : "2", name : "User"},{value : "1", name : "Admin"}] $scope.user = "2"; }) 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script> <div ng-app="app" ng-controller="ctrl" > <select ng-model="user"> <option ng-repeat="i in users" value="{{i.value}}">{{i.name}}</option> </select> Value is : {{user}} </div> 

And now you can use $scope.user as selected value to send wherever you want.

To send it as payload to your request, you can use something like

..
data : {"userLevel" :$scope.user },
..

Use the as clause in ng-options :

<div class="form-group col-md-6">
    <label for="usrlevel">User Level:</label>
    <select class="form-control form-control-sm"
            ̶d̶a̶t̶a̶-̶n̶g̶-̶i̶n̶i̶t̶=̶"̶f̶o̶r̶m̶D̶a̶t̶a̶.̶u̶s̶r̶l̶e̶v̶e̶l̶ ̶=̶ ̶u̶s̶r̶l̶e̶v̶e̶l̶s̶[̶0̶]̶"̶
            data-ng-model="formData.usrlevel"
            ̶d̶a̶t̶a̶-̶n̶g̶-̶o̶p̶t̶i̶o̶n̶s̶=̶"̶x̶.̶n̶a̶m̶e̶ ̶f̶o̶r̶ ̶x̶ ̶i̶n̶ ̶u̶s̶r̶l̶e̶v̶e̶l̶s̶"̶>̶
            data-ng-options="x.value as x.name for x in usrlevels">
    </select>
</div>

Also the initial value of the ng-model should be set to a primitive instead of an object:

$scope.formData.usrlevel = $scope.usrlevels[0].value;

It is better to POST data as application/json , but if your backend only supports application/x-www-form-urlencoded , use the AngularJS built-in param serializer:

$scope.addForm = function() {
    var ans="";
    $http({
        method  : 'POST',
        url     : 'php/addstaff.php',
        ̶d̶a̶t̶a̶ ̶ ̶ ̶ ̶:̶ ̶$̶.̶p̶a̶r̶a̶m̶(̶$̶s̶c̶o̶p̶e̶.̶f̶o̶r̶m̶D̶a̶t̶a̶)̶,̶
        data    : $scope.formData,
        transformRequest: $httpParamSerializerJQLike,
        headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  //set the headers so angular passing info as form data (not request payload)
    })

As others had mentioned, there was a problem with ng-options which is why it returned an object and not just the value.

But then, after changing ng-options it no longer had 'User' as the default selected item in the drop down - and this was then a problem with ng-init .

Old HTML

<select class="form-control form-control-sm"
     data-ng-init="formData.usrlevel = usrlevels[0]"
     data-ng-model="formData.usrlevel"
     data-ng-options="x.name for x in usrlevels">
</select>

New HTML

<select class="form-control form-control-sm" 
   data-ng-model="formData.usrlevel" 
   data-ng-init="formData.usrlevel = formData.usrlevel || usrlevels[0].value"
   data-ng-options="x.value as x.name for x in usrlevels">
</select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM