问题
I have an array of objects ($scope.fields
) that define how input fields should be set up for the $scope.data
object model. The fieldName property is actually the path in the data
Object to the field. Nested objects are separated by a period mark.
eg:
$scope.data = {
user: {
}
}
$scope.fields = [
{fieldName:'user.firstName',fieldLabel:'First Name',dsiabled:false}
{fieldName:'user.location.lat',fieldLabel:'Latitude',dsiabled:false}
{fieldName:'user.location.long',fieldLabel:'Latitude',dsiabled:false}
]
What is the best way in the HTML to bind the $scope.data fields based on the fieldName. I am aware of javascript eval - but is that the best way to do it ? And why does this syntax not work for me ?
ie:
<div ng-repeat="fieldObj in fields">
<dd ng-bind="eval('data.' fieldObj.fieldName)"></dd>
</div>
回答1:
Thanks to @Felix Kling I worked out how to do it.
I used the Object by string idea from Felix_kings ref, and applied a callback function to the ng-bind that received the full object reference.
回答2:
Recently i have developed an Object method to do this job. This single liner recursive approach dynamically accesses any value within an array object structure regardless how deeply nested it is. As per your example
var fields = [
{fieldName:'user.firstName',fieldLabel:'First Name',dsiabled:false},
{fieldName:'user.location.lat',fieldLabel:'Latitude',dsiabled:false},
{fieldName:'user.location.long',fieldLabel:'Latitude',dsiabled:false}
];
Object.prototype.getNestedValue = function(...a) {
return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
document.write(fields.getNestedValue(0,"fieldName"));
For a moredeeply structured object you can always do like
Object.prototype.getNestedValue = function(...a) {
return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
var arr = [{fox: [{turn:[857, 432]}]}, {sax: [{pana:[777, 987]}]}, {ton: [{joni:[123, 567]}]}, {piu: [{burn:[666, 37]}]}, {sia: [{foxy:[404, 696]}]}],
myObj = { foo : 1, bar: { baz : 2 }, bee : 3 };
document.write(arr.getNestedValue(3,"piu",0,"burn",1));
来源:https://stackoverflow.com/questions/30651588/referencing-a-nested-javascript-object-dynamically