数据绑定到Angular中数组的特定项目 [英] Data Binding to a specific item of an array in Angular

查看:191
本文介绍了数据绑定到Angular中数组的特定项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个包含JavaScript对象数组的数据结构,如何使用Angular将该数组中的某个条目绑定到输入字段?

Given a data structure that contains an array of JavaScript objects, how can I bind a certain entry from that array to an input field using Angular?

数据结构如下:

$scope.data = {
    name: 'Foo Bar',
    fields: [
        {field: "F1", value: "1F"},
        {field: "F2", value: "2F"},
        {field: "F3", value: "3F"}
    ]
};

fields数组包含给定结构的多个实例,每个条目都具有field属性和value属性.

The fields array contains several instances of the given structure, with each entry having both a field attribute and a value attribute.

如何使用field F1input控件绑定到数组项的value字段属性?

How can I bind an input control to the value field attribute of the array entry with the field F1?

<input ng-model="???"/>

我知道我可以使用ng-repeat绑定所有字段,但这不是我想要的.上面的数据只是一个更大的字段列表中的示例,我只想将字段的预定义子集绑定到屏幕上的控件.该子集不是基于数组条目中的属性,而是在页面设计时就已知.

I know that I could bind all fields using an ng-repeat, but that's not what I want. The above data is just an example from a much larger list of fields, where I only want to bind a pre-defined subset of fields to controls on the screen. The subset is not based on the attributes in the array entries, but is known at design time of the page.

因此对于上面的示例,我将尝试将F1绑定到页面上的一个输入,并将F2绑定到另一输入. F3不会绑定到控件.

So for the above example, I would try to bind F1 to one input on the page, and F2 to another one. F3 would not be bound to a control.

我已经看到了在ng-model中使用过函数的示例,但是它似乎不适用于Angular 1.1.0.

I've seen examples where a function was used in the ng-model, but it doesn't seem to work with Angular 1.1.0.

还有另一种将输入字段绑定到特定数组条目的聪明方法吗?

Is there another clever way to bind the input field to a specific array entry?

这是一个带有示例的小提琴,但是由于它试图使用ng-model属性中的功能而无法正常工作: http ://jsfiddle.net/nwinkler/cbnAU/4/

Here's a fiddle that has an example, but does not work since it's trying to use function in the ng-model attribute: http://jsfiddle.net/nwinkler/cbnAU/4/

更新

根据下面的建议,它应该是这样的: http://jsfiddle.net/nwinkler/cbnAU/7/

Based on the recommendation below, this is what it should look like: http://jsfiddle.net/nwinkler/cbnAU/7/

推荐答案

我个人将以某种方式使数组的条目的 field 属性成为对象的标识符,从而对数组进行重组.嗯,那句话听起来很奇怪.我的意思是:

I personally would reorganize the array in a way that field property of an entry of the array become the identifier of the object. Mhhh that sentence may sound strange. What I mean is the following:

$scope.data = {
    name: 'F1',
    fields: {
        F1: {
           value: "1F"
        },
        F2: {
           value: "2F"
        }
    }
};

如果您想动态绑定一个值,这是实现它的一种简便快捷的方法. 这是您的小提琴经过修改,使其措辞正确的地方. http://jsfiddle.net/RZFm6/

If you want to bind a the value dynamically and it's an easy and quick way to achieve it. Here is your fiddle modified so that it words. http://jsfiddle.net/RZFm6/

我希望对您有帮助

这篇关于数据绑定到Angular中数组的特定项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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