Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
72
rated 0 times [  75] [ 3]  / answers: 1 / hits: 39758  / 12 Years ago, fri, december 14, 2012, 12:00:00

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?



The data structure looks like this:



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


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



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



<input ng-model=???/>


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.



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.



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?



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/



Update



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


More From » arrays

 Answers
1

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
}
}
};


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/



I hope that helps


[#81418] Thursday, December 13, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chase

Total Points: 78
Total Questions: 106
Total Answers: 93

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
chase questions
Thu, Mar 31, 22, 00:00, 2 Years ago
Thu, Jul 1, 21, 00:00, 3 Years ago
Sat, Dec 12, 20, 00:00, 4 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
;