如何使与选择的元素对象角度NG-模型的工作? [英] How to make angular ng-model work with objects in select elements?
问题描述
从传递一个对象时,选择
元素我有一个选择
元素NG-model的问题。所以,想象一下,我们有柱阵列从一个称为表列
(该表的定义),我们希望在这个定义创造一些过滤器
I have a problem with ng-model on a select
element when passing an object from option
elements. So, imagine we have an array of columns from a table called columns
(the table's definition) and we'd like to creat some filters upon this definition
var columns = [
{name: 'Account ID', type: 'numeric'},
{name: 'Full name', type: 'text'},
{name: 'Date of birth', type: 'date'},
{name: 'Active', type: 'boolean'}
// and so on
];
var filters = [{}];
HTML
<div class="form-field" ng-repeat="filter in filters">
<select ng-model="filter">
<option value="" disabled>Choose filter</option>
<option ng-repeat="column in columns" ng-value="column">{{column.name}}</option>
</select>
<input type="text" ng-model="filter.value">
</div>
正如你所看到的,我想是过滤器
获得列
的值,并添加特定在它的数据,因此在某一个时刻,我的过滤器可以是这样的:
As you can see, I'd like that filter
to get the value of column
and to add specific data in it, so at a certain moment, my filter could be like:
[
{name: 'Account ID', type: 'numeric', value: 123},
{name: 'Active', type: 'boolean', value: 'Yes'}
]
无论如何,我不知道这是这样做的方式,但我想知道我怎么能做到这一点的行为,全无控制器书面很多JS code。
Anyway, I'm not sure this is the way of doing this, but I'd like to know how can I achieve this behavior, withour writing to much js code in the controller.
我做了一些变通方法来开始使用 NG-变化
这个工作,通过了过滤器
和 column.name
,发现在列的列
阵列,获得键入
属性,更新过滤
,但我真的觉得还有一个更简单的答案。
I did some workaround to get this done using ng-change
, passing the filter
and the column.name
, find the column in the columns
array, get the type
property, update the filter
, but I really think that there is a simpler answer to this.
推荐答案
您可以使用 NG选项到选定对象绑定到一个模型:
You can use ng-options to bind the selected object to a model:
<div class="form-field" ng-repeat="filter in filters">
<select ng-options="column.name for column in columns" ng-model="filter.value">
<option value="" disabled>Choose filter</option>
</select>
<input type="text" ng-model="filter.value.name">
</div>
更新答案:
<div class="form-field" ng-repeat="filter in filters">
<select ng-options="column.name for column in columns" ng-model="filters[$index]">
<option value="" disabled>Choose filter</option>
</select>
<input type="text" ng-model="filters[$index].name">
</div>
这篇关于如何使与选择的元素对象角度NG-模型的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!