从AngularJS控制器中的嵌套json获取父数据

时间:2015-05-19 02:45:00

标签: javascript json angularjs

作为我的标题,我想从嵌套的json中获取父数据。 我知道如何用HTML做到这一点。我想知道如何在控制器中做到这一点。

这是我的嵌套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('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();
  };})

感谢有人可以提供帮助。

1 个答案:

答案 0 :(得分:2)

您可以使用angularjs中的forEach函数获取父项的名称和子名称,并循环遍历json数据。

这是代码

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

更新: 如果需要,将父名称推送到children数组并从那里访问它。

这是带有代码

的工作插件

http://embed.plnkr.co/9HCJy554oTSKxrdtiNR4/preview

希望这有帮助!