简体   繁体   中英

Get parent data from nested json in AngularJS controller

As my Title, I'd like to get parent data from nested json. I know how to do it in HTML. And I'd like to know how to do it in controllers.

Here is my directive with nested 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();
  };})

Appreciate if someone could help.

You can get the name of parents and the children names using forEach function in angularjs and looping through the json data.,

Here is the code

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

Update: If you want, push parent name into children array and access it from there.

Here is the working plunker with the code

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

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM