Sajan Nagpal Sajan Nagpal - 1 month ago 17
AngularJS Question

Angular Js ng-repeat iterating over JSON

I am new to stackoverflow, please correct my mistakes.

Following is my JSON:

newTodo = {
title: "task 1",
cat: "category 1",
};


Similarly

newTodo = {
title: "task 2",
cat: "category 1",
};


newTodo = {
title: "task 3",
cat: "category 3",
};


Now in my HTML, how should I write code like:

<li ng-repeat="todo in todos">

{{todo.title}}
{{todo.cat}}

</li>


But above is wrong, I want tasks to be shown category wise like:

category 1: task list
category 2: task list

Please help. Please tell me if question is not clear.

Answer

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.todos = [{
    "title": "Task1",
    "cat": "Cat1"
  }, {
    "title": "Task2",
    "cat": "Cat1"
  }, {
    "title": "Task1",
    "cat": "Cat2"
  }];

  var reduced = {};

  $scope.todos.map(function(item) {
    reduced[item.cat] = reduced[item.cat] || [];
    reduced[item.cat].push(item.title);
  });

  $scope.reducedOutput = reduced;
});
li{
 color: red; 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
 
  <ul ng-repeat="(key, value) in reducedOutput">
    {{key}}
    <li ng-repeat="title in value">{{title}}</li>
  </ul>

</div>