Angular_Newbie
Angular_Newbie

Reputation: 417

How to access Nested JSON Data via Index, Angular JS, ng-click?

I have a List of cars assigned to a person for a particular month. If you search April you will get April data. How do I access Nested JSON data via Index?

Here's plunker

   $scope.cars = $scope.results[resultIndex].cars.map(function(car) {
          return {
        make: car.Make,
            year: car.Year
          };
        });

   $scope.showCars = function(resultIndex) {
      $scope.cars = $scope.results[resultIndex].cars;
    };

      "April": [{
            "Name": "Tim",
                "Address": "Street",
                "Phone": "111",
                "Status": "Speeding",
                "cars": [
                  {
                    "Make": "Honda",
                    "Year": "2000"
                   }, 
                  {
                    "Make": "Ford",
                    "Year": "2010"
                  },
                  {
                    "Make": "Toyota",
                    "Year": "2004"
                  }

            ]},

Upvotes: 1

Views: 1138

Answers (1)

yangli-io
yangli-io

Reputation: 17334

Theres a few things you should first

Now to the code, you should really simplify your logic. Your data structure is all there and you haven't changed it much every time you search for something, so theres no need to map or loop the data - you should only need that if you need to do something with the data.

Your click button function can be as simple as

$scope.clickButton = function(enteredValue) {
    $scope.reset();
    $scope.results = data[enteredValue];
}

Change ur showCars function to

$scope.showCars = function(car) {
    $scope.cars = car;
};

in your html simply change the showCars function call to

<td ng-click='showCars($index)'>{{result.name}}</td>

Remove this, you wont need it

$scope.cars = $scope.results[resultIndex].cars.map(function(car) {
      return {
    make: car.Make,
        year: car.Year
      };
    });

EDIT

Heres the result http://plnkr.co/edit/LGytByq0d3a7AORxXsHa?p=preview

Upvotes: 4

Related Questions