作为我的标题,我想从嵌套的 json 中获取父数据。 我知道如何在 HTML 中做到这一点。我想知道如何在 Controller 中做到这一点。
这是我的嵌套 json 指令
.factory('dataFac', function(){
return {
parents : [{
name: 'George',
age: 44,
children: [{
name: 'Jack',
age: 16
},{
name: 'Amy',
age: 13
}]
}, {
name: 'Jimmy',
age: 38,
children: [{
name: 'Max',
age: 7
},{
name: 'Lily',
age: 5
},{
name: 'Kim',
age: 4
}]
}]
}})
Controller
.controller('dataCtrl', function($scope, $location, dataFac) {
$scope.data = dataFac.parents;
//here I'd like to get name of parents
$scope. = ;
//here I'd like to get name of children
$scope. = ;
//and when I get the data of the children, I can get their parents' name
$scope. = ;
console.log($scope.navbars.id);
$scope.isActive = function(route) {
return route === $location.path();
};})
感谢有人可以提供帮助。
最佳答案
您可以使用 angularjs 中的 forEach 函数并循环 json 数据来获取 parent 的姓名和 child 的姓名。,
这是代码
app.controller('myController', function($scope, dataFac) {
$scope.data = dataFac.parents;
$scope.parentsName = [];
$scope.childName = [];
//here I'd like to get name of parents
angular.forEach(dataFac.parents, function(parent) {
$scope.parentsName.push({
name: parent.name
});
angular.forEach(parent.children, function(child) {
//here I'd like to get name of children
$scope.childName.push({
childName: child.name,
parentName: parent.name
});
});
});
});
更新: 如果需要,请将父级名称插入子级数组并从那里访问它。
这是带有代码的工作插件
http://embed.plnkr.co/9HCJy554oTSKxrdtiNR4/preview
希望这有帮助!
关于javascript - 从 AngularJS Controller 中的嵌套 json 获取父数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30315881/