简体   繁体   English

在AngularJS中选择Option返回对象不值

[英]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; 我仍在学习AngularJS,所以我不太确定实现此目标的最佳方法。 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. 我可以在普通的HTML中做到这一点,但不能使用“ selected”属性,因此我切换到Angular元素-这是我第一次使用。

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". 用户的值为“ 2”,其中管理员的值为“ 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". 我的问题是,当表单(通过AJAX)提交到PHP时,表单正在提交一个对象,例如{value : "2", name : "User"} ,我希望它只提交值,即:“ 2" 。

HTML code: HTML代码:

<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: JavaScript代码:

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. 这是调试器的图像,显​​示对于“ usrlevel”,表单正在提交一个对象,而该对象只应提交所选项目的值。
Thus, in the debugger, it should just be showing usrlevel:"2" 因此,在调试器中,它应该只显示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. 更新:人们似乎给人的印象是,仅AJAX调用应提交用户级别(我认为调试器窗口图像将清楚表明用户级别是表单中的1个元素),这是实际的HTML表单。

<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 这将在选择时将X设置为模型,如果您只希望将名称/ x的任何其他属性设置为模型,则需要使用

  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. 如告诉角度,选择x将其显示为y。

to make default selection work 使默认选择起作用

now you need to update $score.formData.value with value of selected user object. 现在您需要使用所选用户对象的值更新$score.formData.value

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. 最终发送整个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! 再次只传递wt你需要给ajax的数据,不要传递整个对象!

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. 现在,您可以使用$scope.user作为选定值,将其发送到您想要的任何地方。

To send it as payload to your request, you can use something like 要将其作为有效载荷发送到您的请求,您可以使用类似

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

Use the as clause in ng-options : ng-options使用as子句:

<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: ng-model的初始值也应该设置为原始类型,而不是对象:

$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: 最好将数据以application/json ,但是如果您的后端仅支持application/x-www-form-urlencoded ,请使用AngularJS内置的param序列化器:

$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. 正如其他人提到的那样, ng-options存在一个问题,这就是为什么它返回一个对象而不仅仅是返回值的原因。

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 . 但是,在更改ng-options之后,它不再具有“ User”作为下拉列表中的默认选定项-这就是ng-init的问题。

Old HTML 旧的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 新的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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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