2015-06-04 37 views
0

我有一个对象数组($scope.fields),它定义了如何为$scope.data对象模型设置输入字段。 fieldName属性实际上是该字段的data对象中的路径。嵌套对象由句号分隔。动态引用一个嵌套的Javascript对象

如:

$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} 
    ] 

什么是在HTML结合基础上的字段名的$ scope.data领域的最佳途径。我知道JavaScript的eval - 但这是做到这一点的最佳方式?为什么这个语法不适合我?

即:

<div ng-repeat="fieldObj in fields"> 
    <dd ng-bind="eval('data.' fieldObj.fieldName)"></dd> 
</div> 
+1

参见[访问嵌套JavaScript和串键对象( http://stackoverflow.com/q/6491463/218196)...但我不知道如何可以与Angular集成。 *“为什么这个语法不适合我”*推测你不能在'ng-bind'中放入任意表达式。 –

+0

所以技术上我可以ng绑定到一个函数,将返回正确的绑定 - 感谢您的帮助菲利克斯国王。我现在要测试它。 – Andy59469

回答

0

感谢@Felix克林我计算出如何做到这一点。

我使用了来自Felix_kings ref的字符串想法的对象,并将回调函数应用于接收完整对象引用的ng-bind。

0

最近我开发了一个Object方法来完成这项工作。这种单线程递归方法动态地访问数组对象结构中的任何值,而不管它的嵌套深度如何。按照您的例子

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"));

对于moredeeply构造体,你总是可以做到像

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