如何使angularJS ng模型与选择元素中的对象一起使用? [英] How to make angularJS ng-model work with objects in select elements?

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

问题描述

option元素传递对象时,我在select元素上使用ng-model有问题.因此,假设我们有一个来自名为columns(表的定义)的表的列数组,并且我们想根据此定义创建一些过滤器

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>

如您所见,我希望该filter能够获取column的值并在其中添加特定的数据,因此在某个时刻,我的过滤器可能像这样:

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代码的同时实现这种行为.

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-change完成此操作,传递filtercolumn.name,在columns数组中找到列,获取type属性,更新filter,但我真的认为对此有一个更简单的答案.

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-options 将所选对象绑定到模型:

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>

这篇关于如何使angularJS ng模型与选择元素中的对象一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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