我在将数据绑定到angularJs 1.0时面临一个问题。
我通过带有动态列名称的数据透视表
从数据库中获取数据但我无法将数据绑定到angularJs html表达式,
这里的任何人都可以建议我如何实现这一目标。我的数据如下所示。
[{"5V00L":"Charcoal","T200":"No Color","GradeName":"Pre Kindergarten","GradeLevelId":10},{"5V00L":"Sapphire","T200":"Heather Grey & Red","GradeName":"Kindergarten","GradeLevelId":11},{"5V00L":"No Color","T200":"Gold & Navy","GradeName":"1st Grade","GradeLevelId":14},{"5V00L":"No Color","T200":"White & Lime Shock","GradeName":"Grade-Name","GradeLevelId":27}]
在 5V00L 中, T200 是动态列名。 所以,请帮助我如何在我的angulrJs html表达式中绑定这两个列属性,如 object.GradeName
答案 0 :(得分:1)
var obj = { 5V00L: "Charcoal", T200: "No Color", GradeName: "Pre Kindergarten", GradeLevelId: 10};
var firstDynamicVal = obj[Object.keys(obj)[0]];
var secondDynamicVal = obj[Object.keys(obj)[1]];
console.log("First Value: "+firstDynamicVal+", Second Value: "+secondDynamicVal);
你可以尝试这个来获得前两个值。但是,只有当属性的顺序保持不变时,此解决方案才有效。
答案 1 :(得分:1)
花了2-3个小时后才解决这个问题,我找到了以下方法。 我的对象列表是:
[{"5V00L":"Charcoal","T200":"No Color","GradeName":"Pre Kindergarten","GradeLevelId":10},{"5V00L":"Sapphire","T200":"Heather Grey & Red","GradeName":"Kindergarten","GradeLevelId":11},{"5V00L":"No Color","T200":"Gold & Navy","GradeName":"1st Grade","GradeLevelId":14},{"5V00L":"No Color","T200":"White & Lime Shock","GradeName":"Grade-Name","GradeLevelId":27}]
5V00L 和 T200 是两个第一个动态属性。 创建一个角度函数。
$scope.ObjectKey = function (obj) {
return Object.keys(obj);
}
我在我的html中使用过这个函数,如下所示:
<div ng-repeat="color in Colors">
<div style="width: 33%; float: left">
{{color[ObjectKey(color)[0]]}}
</div >
<div style="width: 33%; float: left">
{{color[ObjectKey(color)[1]]}}
</div>
</div>
答案 2 :(得分:0)
根据ECMAScript Third Edition (pdf):
4.3.3对象
对象是Object类型的成员。这是一个无序的 集合属性,每个属性包含一个原始值, 对象或功能。存储在对象属性中的函数是 称为方法。
这意味着您无法确定自定义属性是否包含0和1索引。
不是希望它们永远是第一个,更好的方法是用ng-repeat
循环列出所有属性并隐藏预定义的属性。
HTML:
<div ng-repeat="item in list">
<div ng-repeat="(key, value) in item">
<p ng-hide="!isCustomProperty(key)">
<b ng-bind="key"></b>: <span ng-bind="value"></span>
</p>
</div>
</div>
JS:
var predefinedProperties = ['GradeName', 'GradeLevelId'];
$scope.isCustomProperty = function (prop) {
return predefinedProperties.indexOf(prop) < 0;
};
此处jsfiddle带有工作示例
<强>更新强>
甚至更好的解决方案是将动态属性存储为对象数组。
例如:
[{
"GradeName":"Pre Kindergarten",
"GradeLevelId":10,
"Attributes": [
{
"key": "5V00L",
"value": "Charcoal"
}, {
"key": "T200",
"value": "No Color"
}
]
}, {
"GradeName":"Kindergarten",
"GradeLevelId":11,
"Attributes": [
{
"key": "5V00L",
"value": "Sapphire"
}, {
"key": "T200",
"value": "Heather Grey & Red"
}
]
}, {
"GradeName":"1st Grade",
"GradeLevelId":14,
"Attributes": [
{
"key": "5V00L",
"value": "No Color"
}, {
"key": "T200",
"value": "Gold & Navy"
}
]
}, {
"GradeName":"Grade-Name",
"GradeLevelId":27,
"Attributes": [
{
"key": "5V00L",
"value": "No Color"
}, {
"key": "T200",
"value": "White & Lime Shock"
}
]
}];