【问题标题】:Angualrjs dropdown select box reading Json object textAngularjs下拉选择框读取Json对象文本
【发布时间】:2015-10-08 11:18:42
【问题描述】:

我正在尝试做的是从 json 数据中读取文本的下拉选择。我不知何故无法读取该值,我不知道为什么。

这是我的代码

我的下拉框:

   <label class="item item-input item-select">
                <b class="input-label">Claim Type:</b>
                <select ng-model="claimType" required>
                  <option value="Select claim" title="Select Claim" selected disabled>Claim Type</option>
                  <option ng-repeat="claim in claimType " value="{{claim.value}}"
                          ng-selected="{{claim.value== claimType}}">
                          {{claim.text}} 
                              </option>
                            </select>
                        </label>

我的 Json 对象

 angular.module('app')
        .factory('WebApi', function () {

            var claimType = [{
                value: "Car",
                text: "Car",
            }, {
                value: "Boat",
                text: "Boat",
            }, {
                value: "Others",
                text: "Others"
            }]
        })
 //Display 50 items randomly
   var tempData = [];
        for (var i = 0; i < 50; i++) {
                    var selectedClaimType = claimType[Math.floor((Math.random() * claimType.length))];
                   tempData.push({
                        claimType: selectedClaimType.text,
                    })
                };
            return {
              getClaimTypes: function () {

                    return selectedClaimType.text;
                },
            }

在我的控制器中,我调用了

$scope.claimType = WebApi.getClaimTypes();

【问题讨论】:

    标签: json angularjs angularjs-service


    【解决方案1】:

    您可以使用ng-options 来帮助管理选择列表。

    <label class="item item-input item-select">
        <b class="input-label">Claim Type:</b>
        <select ng-model="claimType" required
          ng-options="transport.text for transport in traffic">
          <option value="" title="Select Claim" selected disabled>Claim Type</option>
        </select>
    </label>
    

    这会将选定的transport 绑定到claimType。如果您希望为 claimType 分配 transport.value 的值,您可以这样做:

    <label class="item item-input item-select">
        <b class="input-label">Claim Type:</b>
        <select ng-model="claimType" required
          ng-options="transport.text as transport.value for transport in traffic">
          <option value="" title="Select Claim" selected disabled>Claim Type</option>
        </select>
    </label>
    

    【讨论】:

    • 感谢您的快速回复,如果我有这样的事情怎么办?我注意到我不能这样做,因为我有随机属性,你知道如何解决这个问题吗?我需要那个 for 循环,因为我想显示 50 个虚拟数据。谢谢
    • 您的代码显示您创建了一个 tempData 数组并将一些值推入其中,但我没有看到您在选择列表绑定中使用该“随机”数组的位置......跨度>
    • 事实上,您的工厂似乎并没有返回您所期望的;你想要一个数组,但你实际返回的是一个单一的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多