如何在选择ng-options angular中组合多个对象属性

时间:2017-02-24 16:37:01

标签: javascript angularjs

我想在我的选择选项中显示文字和数字。 JSON具有不同的文本和数字属性,我需要将它们组合起来并默认显示在选择的选项值中。

预期产出: 000.000.0001 - 芝加哥

HTML:

<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <link rel="stylesheet" href="style.css">
  <script>document.write("<base href=\"" + document.location + "\" />");</script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">  
  <select ng-model="model.selected" ng-options="item.ID as item.Title for item in items"></select>
  <p>Selected: {{model.selected}}</p>  
</body>
</html>

JS:

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

app.controller('MainCtrl', function($scope) {
  $scope.items = [
       {ID: '000.000.0001', Title: 'Chicago'},
       {ID: '000.000.0002', Title: 'New York'},
       {ID: '000.000.0003', Title: 'Washington'}
    ];  
});

1 个答案:

答案 0 :(得分:1)

您可以使用此方法分配多个值

  <select ng-model="model.selected" ng-options="item.ID  as item.ID + '-' + item.Title for item in items"></select>
  <p>Selected: {{model.selected}}</p> 

&#13;
&#13;
angular.module("app",[])
.controller("ctrl",function($scope){

  $scope.model = {
    selected : '000.000.0001'
  }
	$scope.items = [
       {ID: '000.000.0001', Title: 'Chicago'},
       {ID: '000.000.0002', Title: 'New York'},
       {ID: '000.000.0003', Title: 'Washington'}
    ];  
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<select ng-model="model.selected" ng-options="item.ID  as item.ID + '-' + item.Title for item in items"></select>
  <p>Selected: {{model.selected}}</p>  
</div>
&#13;
&#13;
&#13;