Mel*_*vin 21 javascript json angularjs
我有以下json对象:
$scope.values = [
{
"id": 2,
"code": "Code 1",
"name": "Sample 1"
},
{
"id": 4,
"code": "Code 2",
"name": "Sample 2"
},
{
"id": 7,
"code": "Code 3",
"name": "Sample 3"
}
];
Run Code Online (Sandbox Code Playgroud)
在select标签中,我有:
<select name="c_id" ng-options="c.id as c.code for c in values"></select>
Run Code Online (Sandbox Code Playgroud)
生成的选择选项是:
Code 1
Code 2
Code 3
Run Code Online (Sandbox Code Playgroud)
有没有办法格式化选项中的文本,如下所示?
Code 1 -- Sample 1
Code 2 -- Sample 2
Code 3 -- Sample 3
Run Code Online (Sandbox Code Playgroud)
或者我只需要在将它们附加到模型之前准备好值?任何帮助表示赞赏.谢谢.
Che*_*niv 47
您可以使用以下语法执行此操作:
ng-options="c.id as (c.code + ' -- '+ c.name) for c in values"
Run Code Online (Sandbox Code Playgroud)
示例:http://jsfiddle.net/cherniv/6EkL7/1/
或者有人可能会喜欢下一个语法
ng-options="c.id as [c.code,c.name].join(' -- ') for c in values"
Run Code Online (Sandbox Code Playgroud)
示例:http://jsfiddle.net/cherniv/6EkL7/2/
但在某些情况下,使用过滤器是合理的,例如:
app.filter("formatter",function(){
return function(item){
return item.code+ " -- " + item.name;
}
})
Run Code Online (Sandbox Code Playgroud)
和: ng-options="c.id as c|formatter for c in values"
示例:http://jsfiddle.net/cherniv/K8572/
当然,你可以通过调用做到这一点ng-repeat的option,
的HTML
<select>
<option ng-repeat="v in values" value="{{v.id}}">
{{v.code}} -- {{v.name}}
</option>
</select>
Run Code Online (Sandbox Code Playgroud)
JS
相同
演示版 Fiddle
| 归档时间: |
|
| 查看次数: |
9905 次 |
| 最近记录: |