angularjs从select中提取多个值

时间:2014-05-13 16:07:59

标签: angularjs

我是Angularjs的新手,我的选择

有问题

我填充了我的选择字段,但是当我想显示从json中选择的内容时,我只能提取一个值。我需要名称和类型,但在我的网页中有两个不同的地方

小提琴是http://jsfiddle.net/ktcle/9Ymvt/1455/

<div ng-controller="MyCtrl">
  <select ng-options="style.name as style.name for style in styles" ng-model="style">
     <option style="display:none" value="">select a style</option>
  </select>

  <h2>selected: {{style}}</h2>

  <h3>type: {{styles.type}}</h3>

</div>

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
$scope.styles = [
    {
    name: "Red",
    code: "123",
    type: "t-shirt"
    },
{
    name: "Yellow",
    code: "456",
    type: "vest"
    },
{
    name: "Green",
    code: "789",
    type: "jumper"
    },
    ];
}

2 个答案:

答案 0 :(得分:0)

将整个style对象指定为ng-options表达式中的值。并且,将ng-model绑定到ng-options之外定义的内容。

<select ng-options="style as style.name for style in styles" ng-model="selected.style">

http://jsfiddle.net/9Ymvt/1456/

答案 1 :(得分:0)

两件事:

  1. 将您的ng-options重写为"style.name for style in styles"。你拥有它的方式将显示style.name并选择style.name。您想要选择样式
  2. 对于类型,您的样式变量被错误地复数化。应该是:<h3>type: {{style.type}}</h3>
  3. <div ng-controller='MyCtrl'>
      <select ng-options="style.name for style in styles" ng-model="style">
         <option style="display:none" value="">select a style</option>
      </select>
    
      <h2>selected: {{style}}</h2>
    
      <h3>type: {{style.type}}</h3>
    
    </div>
    

    这是您更新的jsFiddle:http://jsfiddle.net/mnibecker/B2wJ4/