0

Here I have a JSON like this:

{"years":[
  {
    "year_title":"94",
    "months":[...]
  }
  {
    "year_title":"95",
    "months":[...]
  }
  {
    "year_title":"96",
    "months":[...]
  }
]}

and I have managed to show it's data with following code:

<div ng-repeat="year in event.years">
    <h1>{{year.year_title}}</h1>
    <div ng-repeat="month in year.months">
        <h3> {{month.month_title}} </h3>
    </div>
</div>

So it obviously shows me my whole data (all years, all months). but what if I want to show only months of specific year.!? thanks guys...

2

2 Answers 2

1

try angularjs built-in filter, don't need custom filter at all. And you can change 94 to be a variable.

ng-repeat="year in event.years | filter: {year_title: '94'}"

refer demo below:

angular.module("app", [])
  .controller("myCtrl", function($scope) {
    $scope.event = {
      "years": [{
        "year_title": "94",
        "months": [{
          month_title: 'jan'
        }]
      }, {
        "year_title": "95",
        "months": [{
          month_title: 'feb'
        }]
      }, {
        "year_title": "96",
        "months": [{
          month_title: 'dec'
        }]
      }]
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  <div ng-repeat="year in event.years | filter: {year_title: '94'}">
    <h1>{{year.year_title}}</h1>
    <div ng-repeat="month in year.months">
      <h3> {{month.month_title}} </h3>
    </div>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome job man. Where have you been so far!? I was eating google to find the solution :D.
1

use you own filter like:

<div ng-repeat="year in event.years | year">
<h1>{{year.year_title}}</h1>
<div ng-repeat="month in year.months">
    <h3> {{month.month_title}} </h3>
</div>

var someApp=angular.module('someApp', []);

 someApp.filter('year', function() {
return function(input, uppercase) {
    var out = [];
    for (var i = 0; i < input.length; i++) {
        if(input[i].year === 95){
            out.push(input[i]);
        }
    }
    return out;
}

});

2 Comments

if(input[i].year === 95) it says unresolved variable year.
i've change code try now, or provide jsfiddle i'll help you out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.