如何使与选择的元素对象角度NG-模型的工作? [英] How to make angular ng-model work with objects in select elements?

查看:114
本文介绍了如何使与选择的元素对象角度NG-模型的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

传递一个对象时,选择元素我有一个选择元素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>

Plunker

更新答案:

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆