简体   繁体   English

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

[英]Angular select with ng-repeat doesnt work on json object

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

The Above code works but it leaves me unable to retrieve the id field of the option element. 上面的代码有效,但使我无法检索option元素的id字段。 See the different Plunker - working example with value={{option.id}} https://plnkr.co/edit/?p=preview - example with value={{option}} https://plnkr.co/edit/iEoHaSYLZbnwId8zHi9U?p=preview . 查看不同的Plunker- value={{option.id}}工作示例https://plnkr.co/edit/?p=preview- value={{option}} https://plnkr.co/edit / iEoHaSYLZbnwId8zHi9U?p = preview

If I use ng-options in select it works - https://plnkr.co/edit/iEoHaSYLZbnwId8zHi9U?p=preview . 如果我在选择中使用ng-options- https://plnkr.co/edit/iEoHaSYLZbnwId8zHi9U?p=preview

Do I need to filter ng-model? 我需要过滤ng-model吗?

You can't retrieve the id because by passing the option object in value you're converting it to a string, so data.model became "{"id":"1","name":"Option A"}" . 您无法检索ID,因为通过将value传递给选项对象,您会将其转换为字符串,因此data.model变为"{"id":"1","name":"Option A"}" In order to pass the object use instead ng-value: 为了传递对象,请改用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>

What I understand from your question the below code should work 我从您的问题中了解到以下代码应该有效

<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>

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

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