使用ng-repeat的角度选择不适用于json对象

时间:2018-01-05 09:52:27

标签: javascript angularjs json

<select name="repeatSelect" id="repeatSelect" ng-model="data.model">
  <option ng-repeat="option in data.availableOptions" value="{{option}}">{{option.name}}</option>
</select>

上面的代码有效,但是我无法检索选项元素的id字段。通过value={{option.id}} https://plnkr.co/edit/?p=preview查看不同的Plunker工作示例 - 示例与value={{option}} https://plnkr.co/edit/iEoHaSYLZbnwId8zHi9U?p=preview

如果我在选择它时使用ng-options工作 - https://plnkr.co/edit/iEoHaSYLZbnwId8zHi9U?p=preview

我是否需要过滤ng-model?

2 个答案:

答案 0 :(得分:1)

您无法检索ID,因为通过在value中传递选项对象,您将其转换为字符串,因此data.model变为"{"id":"1","name":"Option A"}"。为了传递对象,请使用ng-value:

  <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
    <option ng-repeat="option in data.availableOptions" ng-value="{{option}}">{{option.name}}</option>
  </select>

答案 1 :(得分:0)

我从您的问题中理解以下代码应该有效

<body ng-app="ngrepeatSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <label for="repeatSelect"> Repeat select: </label>
    <!--<select name="repeatSelect" id="repeatSelect" ng-model="data.model" ng-options="option as option.name for option in data.availableOptions">-->
    <!--    </select>-->
<select name="repeatSelect" id="repeatSelect" ng-model="data.model">
  <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
</select>
  </form>
  <hr>
  <tt>model = {{data.model}}</tt><br/>
</div>
</body>