【问题标题】:Why AngularJS ng-model return [object%20Object] as value and not the option value (integer)?为什么 AngularJS ng-model 返回 [object%20Object] 作为值而不是选项值(整数)?
【发布时间】:2017-05-11 16:09:27
【问题描述】:

我在 AngularJS 中有一个选择,例如:

<select class="browser-default" ng-model="newParticipantFormData.groupId" ng-options="item as item.name for item in newParticipantFormData.availableGroups.results track by item.id">

                    </select>

我希望当用户在“选择”中选择一个值时,我得到 newParticipantFormData.groupId 中的值,但我得到的是:[object%20Object],为什么?

在控制台中我可以看到值,如下所示:

 <option value="?" selected="selected" label=""></option>
 <option value="1819" label="Grupo 147258">Grupo 147258</option>
 <option value="1820" label="Grupo 258369">Grupo 258369</option>

【问题讨论】:

    标签: javascript angularjs arrays json


    【解决方案1】:

    如果您想在选择选项时传递项目 ID,请尝试以下操作

    ng-options="item.id as item.name for item in newParticipantFormData.availableGroups.results"
    

    而不是

    ng-options="item as item.name for item in newParticipantFormData.availableGroups.results"
    

    演示

    var myApp = angular.module('myApp',[]);
    
    myApp.controller('MyCtrl', function ($scope) {
        $scope.newParticipantFormData = {
          "availableGroups" : { "results" : [
             {
               "id": 1819,
               "name": "Grupo 147258"
             },
             {
               "id": 1820,
               "name": "Grupo 258369"
             }
          ]}
        }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="MyCtrl">
      <select class="browser-default" ng-model="newParticipantFormData.groupId" ng-options="item.id as item.name for item in newParticipantFormData.availableGroups.results"></select>
      {{newParticipantFormData.groupId}}
    </div>

    【讨论】:

      【解决方案2】:

      试试这个

      <select class="browser-default" ng-model="newParticipantFormData.groupId">
          <option ng-repeat="participant in newParticipantFormData.availableGroups.results" value="{{$index}}">{{participant}}</option>
      </select>
      

      值不应该是索引,它可以是你需要的任何东西。

      【讨论】:

        【解决方案3】:

        我认为您需要将ng-options 更改如下

         ng-options="item.id as item.name for item in newParticipantFormData.availableGroups.results track by item.id"
        

        【讨论】:

        • 不起作用,选择不要让选择任何值,仍然是空白但使用您的代码的值在那里。
        猜你喜欢
        • 2022-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-29
        • 1970-01-01
        • 1970-01-01
        • 2018-05-24
        • 1970-01-01
        相关资源
        最近更新 更多