AngularJS: Custom Sorting Function using OrderBy - angularjs

I am attempting to define my own sorting function using the documentation provided at http://docs.angularjs.org/api/ng.filter:orderBy.
Before I explain the code written, I will also mention the behaviour that I am expecting.
I have a table which contains a table header(th) and table data(td). When the user clicks on a column in the table (by column, I mean the th), the table data must sort based on the value in that column.
If the user clicks the same column again, then the sorting is changed to ascending / descending if the previous sorting criteria was descending / ascending respectively.
The user can sort using multiple columns. The first column selected is give the first priority. In case the first column value is the same, then the second column selected for sorting is used.
Now for the code. It can be found here: http://jsfiddle.net/xkjmv/
Problem is that the customSortFunction returns the array as expected, but the sorting does not work - when the user clicks on the column header, the sorting should be either ascending or descending (basically toggle each time it is clicked).
I want to return an array of string predicates since I will have multiple columns to sort, but a single column sort using string predicate itself is not working
EDIT: You can check the console to see the output that the custom sort function returns, if it is not obvious from the code.

In this plunker you can find an example of what you'r looking for with other stuff, hope this help.
Update:
As blazemonger requested the code:
Controllers.js:
app.controller('ctrlRead', ['$scope', '$filter', 'Items', function($scope, $filter, Items) {
// init
$scope.sortingOrder = sortingOrder;
$scope.reverse = false;
$scope.filteredItems = [];
$scope.groupedItems = [];
$scope.itemsPerPage = 5;
$scope.pagedItems = [];
$scope.currentPage = 0;
//#####################################
// get the items from the Items service
Items.then(function(data){
$scope.items = data;
$scope.search();
});
//#####################################
var searchMatch = function (haystack, needle) {
if (!needle) {
return true;
}
return haystack.toLowerCase().indexOf(needle.toLowerCase()) !== -1;
};
// init the filtered items
$scope.search = function () {
$scope.filteredItems = $filter('filter')($scope.items, function (item) {
for(var attr in item) {
if (searchMatch(attr, $scope.query)){
return true;
}
}
return false;
});
// take care of the sorting order
if ($scope.sortingOrder !== '') {
$scope.filteredItems = $filter('orderBy')($scope.filteredItems, $scope.sortingOrder, $scope.reverse);
}
$scope.currentPage = 0;
// now group by pages
$scope.groupToPages();
};
// calculate page in place
$scope.groupToPages = function () {
$scope.pagedItems = [];
for (var i = 0; i < $scope.filteredItems.length; i++) {
if (i % $scope.itemsPerPage === 0) {
$scope.pagedItems[Math.floor(i / $scope.itemsPerPage)] = [ $scope.filteredItems[i] ];
} else {
$scope.pagedItems[Math.floor(i / $scope.itemsPerPage)].push($scope.filteredItems[i]);
}
}
};
$scope.range = function (start, end) {
var ret = [];
if (!end) {
end = start;
start = 0;
}
for (var i = start; i < end; i++) {
ret.push(i);
}
return ret;
};
$scope.prevPage = function () {
if ($scope.currentPage > 0) {
$scope.currentPage--;
}
};
$scope.nextPage = function () {
if ($scope.currentPage < $scope.pagedItems.length - 1) {
$scope.currentPage++;
}
};
$scope.setPage = function () {
$scope.currentPage = this.n;
};
// change sorting order
$scope.sort_by = function(newSortingOrder) {
if ($scope.sortingOrder == newSortingOrder){
$scope.reverse = !$scope.reverse;
}
$scope.sortingOrder = newSortingOrder;
// icon setup
$('th i').each(function(){
// icon reset
$(this).removeClass().addClass('icon-sort');
});
if ($scope.reverse){
$('th.'+newSortingOrder+' i').removeClass().addClass('icon-chevron-up');
}else{
$('th.'+newSortingOrder+' i').removeClass().addClass('icon-chevron-down');
}
};
}]);
app.js:
var app = angular.module('plunker', []);
items.json:
[
{
"ProgramCode":"3DS",
"ProgramGroup":"NCIM",
"EventCode":"20130424TX3DS",
"StartDate":"2013-04-22 00:00:00",
"FormalDate":"April 22-24, 2013",
"LocCity":"Richardson",
"LocState":"TX",
"LocAddress":"3400 Waterview Parkway, #200",
"LocName":"America First Insurance Company",
"Price":"0.00",
"LicenseeURL":null,
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"1",
"LocLatitude":"32.9695",
"LocLongitude":"-96.7409",
"EventType":"SSIH",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"Richardson, TX",
"cls":"LIMITED_SEATS"
},
{
"ProgramCode":"PA",
"ProgramGroup":"CISR",
"EventCode":"20130422SDPA",
"StartDate":"2013-04-22 00:00:00",
"FormalDate":"April 22, 2013",
"LocCity":"Rapid City",
"LocState":"SD",
"LocAddress":"445 Mt. Rushmore Road",
"LocName":"Adoba Eco Hotel Rapid City \/ Mt. Rushmore",
"Price":"150.00",
"LicenseeURL":null,
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"19",
"LocLatitude":"44.0853",
"LocLongitude":"-103.213",
"EventType":"SS",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"Rapid City, SD",
"cls":"LIMITED_SEATS"
},
{
"ProgramCode":"RME",
"ProgramGroup":"CRM",
"EventCode":"20130425FLRME",
"StartDate":"2013-04-22 00:00:00",
"FormalDate":"April 22-25, 2013",
"LocCity":"Orlando",
"LocState":"FL",
"LocAddress":"8101 World Center Dr.",
"LocName":"Caribe Royale",
"Price":"430.00",
"LicenseeURL":"http:\/\/www.faia.com\/PV\/Core\/Events\/Events.aspx",
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"32",
"LocLatitude":"28.3916",
"LocLongitude":"-81.4734",
"EventType":"LSIHOERS",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"Orlando, FL",
"cls":""
},
{
"ProgramCode":"ALM",
"ProgramGroup":"CISR",
"EventCode":"20130423MNALM",
"StartDate":"2013-04-23 00:00:00",
"FormalDate":"April 23, 2013",
"LocCity":"Shoreview",
"LocState":"MN",
"LocAddress":"1000 Gramsie Road",
"LocName":"Hampton Inn",
"Price":"0.00",
"LicenseeURL":"http:\/\/www.iiaba.net\/MN\/03_Education\/01_Calender\/NAV_EDUCalendar?ContentPreference=MN&ActiveState=MN&ActiveTab=NA&ContentLevel1=EDUCTN&ContentLevel2=EDUCAL",
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"40",
"LocLatitude":"45.0856",
"LocLongitude":"-93.1353",
"EventType":"LS",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"Shoreview, MN",
"cls":""
},
{
"ProgramCode":"AO",
"ProgramGroup":"CISR",
"EventCode":"20130423ILAO",
"StartDate":"2013-04-23 00:00:00",
"FormalDate":"April 23, 2013",
"LocCity":"Bannockburn",
"LocState":"IL",
"LocAddress":"1500 South Lakeside Drive",
"LocName":"Mesirow Financial",
"Price":"0.00",
"LicenseeURL":"https:\/\/protech.piiai.org\/Events\/CalendarEventsListView.aspx",
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"40",
"LocLatitude":"42.1693",
"LocLongitude":"-87.8656",
"EventType":"LS",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"Bannockburn, IL",
"cls":""
},
{
"ProgramCode":"AO",
"ProgramGroup":"CISR",
"EventCode":"20130423TXAO",
"StartDate":"2013-04-23 00:00:00",
"FormalDate":"April 23, 2013",
"LocCity":"Richardson (North Dallas)",
"LocState":"TX",
"LocAddress":"900 East Lookout Drive",
"LocName":"Renaissance Dallas-Richardson Hotel",
"Price":"169.00",
"LicenseeURL":"http:\/\/www.iiah.org\/displaycommon.cfm?an=1&SUBARTICLENBR=228",
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"16",
"LocLatitude":"32.9934",
"LocLongitude":"-96.659",
"EventType":"SS",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"Richardson (North Dallas), TX",
"cls":"LIMITED_SEATS"
},
{
"ProgramCode":"FUN",
"ProgramGroup":"CSRM",
"EventCode":"20130423CAFUN",
"StartDate":"2013-04-23 00:00:00",
"FormalDate":"April 23, 2013",
"LocCity":"San Bernardino",
"LocState":"CA",
"LocAddress":"1950 S. Sunwest Lane, Suite 102",
"LocName":"SCS JPA Conference Center",
"Price":"179.00",
"LicenseeURL":null,
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"16",
"LocLatitude":"34.0807",
"LocLongitude":"-117.274",
"EventType":"SS",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"San Bernardino, CA",
"cls":"LIMITED_SEATS"
},
{
"ProgramCode":"IP",
"ProgramGroup":"CISR",
"EventCode":"20130423MAIP",
"StartDate":"2013-04-23 00:00:00",
"FormalDate":"April 23, 2013",
"LocCity":"Peabody",
"LocState":"MA",
"LocAddress":"43 Newbury Street",
"LocName":"Springhill Suites by Marriott",
"Price":"0.00",
"LicenseeURL":"http:\/\/www.massagent.com\/education\/cisr.cfm",
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"27",
"LocLatitude":"42.534",
"LocLongitude":"-70.9615",
"EventType":"LS",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"Peabody, MA",
"cls":""
},
{
"ProgramCode":"IP",
"ProgramGroup":"CISR",
"EventCode":"20130423MIIP",
"StartDate":"2013-04-23 00:00:00",
"FormalDate":"April 23, 2013",
"LocCity":"Troy",
"LocState":"MI",
"LocAddress":"2601 West Big Beaver Road",
"LocName":"Somerset Inn",
"Price":"0.00",
"LicenseeURL":"http:\/\/www.michagent.org\/eweb\/DynamicPage.aspx?Site=AgentNet2&WebKey=2847b6dd-e47d-40ea-b5d1-504c5ff0f800",
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"46",
"LocLatitude":"42.5635",
"LocLongitude":"-83.1841",
"EventType":"LS",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"Troy, MI",
"cls":""
},
{
"ProgramCode":"PA",
"ProgramGroup":"CISR",
"EventCode":"20130423CAPA",
"StartDate":"2013-04-23 00:00:00",
"FormalDate":"April 23, 2013",
"LocCity":"Santa Clara (San Jose)",
"LocState":"CA",
"LocAddress":"5201 Great America Parkway",
"LocName":"Network Meeting Center",
"Price":"169.00",
"LicenseeURL":null,
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"17",
"LocLatitude":"37.3932",
"LocLongitude":"-121.961",
"EventType":"SS",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"Santa Clara (San Jose), CA",
"cls":"LIMITED_SEATS"
},
{
"ProgramCode":"PA",
"ProgramGroup":"CISR",
"EventCode":"20130423CTPA",
"StartDate":"2013-04-23 00:00:00",
"FormalDate":"April 23, 2013",
"LocCity":"Middletown",
"LocState":"CT",
"LocAddress":"213 Court Street",
"LocName":"MiddleOak",
"Price":"0.00",
"LicenseeURL":"http:\/\/www.pia.org\/EDU\/schedule.php?state=CT",
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"40",
"LocLatitude":"41.5537",
"LocLongitude":"-72.6632",
"EventType":"LS",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"Middletown, CT",
"cls":""
},
{
"ProgramCode":"PA",
"ProgramGroup":"CISR",
"EventCode":"20130423WVPA",
"StartDate":"2013-04-23 00:00:00",
"FormalDate":"April 23, 2013",
"LocCity":"Charleston",
"LocState":"WV",
"LocAddress":"129 Summers Street",
"LocName":"Summit Conference Center",
"Price":"150.00",
"LicenseeURL":"http:\/\/www.ohiopia.com",
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"4",
"LocLatitude":"38.3506",
"LocLongitude":"-81.6303",
"EventType":"SS",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"Charleston, WV",
"cls":"LIMITED_SEATS"
},
{
"ProgramCode":"PR",
"ProgramGroup":"CISR",
"EventCode":"20130423MEPR",
"StartDate":"2013-04-23 00:00:00",
"FormalDate":"April 23, 2013",
"LocCity":"South Portland",
"LocState":"ME",
"LocAddress":"363 Maine Mall Road",
"LocName":"DoubleTree by Hilton",
"Price":"0.00",
"LicenseeURL":"http:\/\/www.massagent.com\/education\/cisr.cfm",
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"10",
"LocLatitude":"43.6315",
"LocLongitude":"-70.2727",
"EventType":"LS",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"South Portland, ME",
"cls":""
},
{
"ProgramCode":"PR",
"ProgramGroup":"CISR",
"EventCode":"20130423MOPR",
"StartDate":"2013-04-23 00:00:00",
"FormalDate":"April 23, 2013",
"LocCity":"Springfield",
"LocState":"MO",
"LocAddress":"2720 North Glenstone",
"LocName":"Holiday Inn Hotel and Suites",
"Price":"0.00",
"LicenseeURL":"http:\/\/www.iiaa.org\/MO\/03_Education\/01_Calender\/NAV_EDUCalender?ContentPreference=MO&ActiveState=MO&ActiveTab=STATE&ContentLevel1=EDUCTN&ContentLevel2=EDUCAL",
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"40",
"LocLatitude":"37.2571",
"LocLongitude":"-93.2902",
"EventType":"LS",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"Springfield, MO",
"cls":""
},
{
"ProgramCode":"PR",
"ProgramGroup":"CISR",
"EventCode":"20130423NCPR",
"StartDate":"2013-04-23 00:00:00",
"FormalDate":"April 23, 2013",
"LocCity":"Greensboro",
"LocState":"NC",
"LocAddress":"414 Gallimore Dairy Rd.",
"LocName":"BB&T Greensboro",
"Price":"0.00",
"LicenseeURL":"http:\/\/members.iianc.com\/wcm\/IIANC_Members\/Events\/List\/Core\/Events\/Events.aspx?hkey=90e5e7da-2e1f-4674-ae30-7c12ced0885c",
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"16",
"LocLatitude":"36.0839",
"LocLongitude":"-79.9412",
"EventType":"LSIH",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"Greensboro, NC",
"cls":""
},
{
"ProgramCode":"PR",
"ProgramGroup":"CISR",
"EventCode":"20130423NMPR",
"StartDate":"2013-04-23 00:00:00",
"FormalDate":"April 23, 2013",
"LocCity":"Albuquerque",
"LocState":"NM",
"LocAddress":"2600 Louisiana, NE",
"LocName":"Sheraton Albuquerque Uptown",
"Price":"145.00",
"LicenseeURL":null,
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"15",
"LocLatitude":"35.1064",
"LocLongitude":"-106.579",
"EventType":"SS",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"Albuquerque, NM",
"cls":"LIMITED_SEATS"
},
{
"ProgramCode":"PR",
"ProgramGroup":"CISR",
"EventCode":"20130423SDPR",
"StartDate":"2013-04-23 00:00:00",
"FormalDate":"April 23, 2013",
"LocCity":"Rapid City",
"LocState":"SD",
"LocAddress":"445 Mt. Rushmore Road",
"LocName":"Adoba Eco Hotel Rapid City \/ Mt. Rushmore",
"Price":"150.00",
"LicenseeURL":null,
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"18",
"LocLatitude":"44.0853",
"LocLongitude":"-103.213",
"EventType":"SS",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"Rapid City, SD",
"cls":"LIMITED_SEATS"
},
{
"ProgramCode":"SR",
"ProgramGroup":"CISR",
"EventCode":"20130423ORSR",
"StartDate":"2013-04-23 00:00:00",
"FormalDate":"April 23, 2013",
"LocCity":"Portland",
"LocState":"OR",
"LocAddress":"8931 SE Foster Road Suite 200",
"LocName":"Assurety Northwest",
"Price":"0.00",
"LicenseeURL":"http:\/\/www.piawest.com\/calendar-of-events",
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"40",
"LocLatitude":"45.4786",
"LocLongitude":"-122.562",
"EventType":"LS",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"Portland, OR",
"cls":""
},
{
"ProgramCode":"ADM",
"ProgramGroup":"CSRM",
"EventCode":"20130424CAADM",
"StartDate":"2013-04-24 00:00:00",
"FormalDate":"April 24, 2013",
"LocCity":"San Bernardino",
"LocState":"CA",
"LocAddress":"1950 S. Sunwest Lane, Suite 102",
"LocName":"SCS JPA Conference Center",
"Price":"179.00",
"LicenseeURL":null,
"GateKeeper_length":"0",
"GateKeeperHTML":null,
"SeatsAreAvailable":"18",
"LocLatitude":"34.0807",
"LocLongitude":"-117.274",
"EventType":"SS",
"LocationUnivURL":null,
"UnivCourseNumber":null,
"UnivCourseType":"",
"UnivFaculty":null,
"Course_Type":"San Bernardino, CA",
"cls":"LIMITED_SEATS"
}
]
service.js:
app.factory('Items', ['$http', function($http){
var Url = "items.json";
var Items = $http.get(Url).then(function(response){
return response.data;
});
return Items;
}]);
index.html:
<!doctype html>
<html ng-app="plunker">
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link
rel="stylesheet"
href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css"
>
<link rel="stylesheet" href="style.css">
<link
rel="stylesheet"
href="//netdna.bootstrapcdn.com/font-awesome/3.0.2/css/font-awesome.css"
>
</head>
<body>
<script>
var sortingOrder = 'name';
</script>
<div ng-controller="ctrlRead">
<div class="input-append">
<input
type="text"
ng-model="query"
ng-change="search()"
placeholder="Search"
class="input-large search-query"
>
<span class="add-on"><i class="icon-search"></i></span>
</div>
<table class="table table-striped table-condensed table-hover">
<thead>
<tr>
<th class="LocName">
Id
<a ng-click="sort_by('LocName')">
<i class="icon-sort"></i>
</a>
</th>
<th class="Price">
Name
<a ng-click="sort_by('Price')">
<i class="icon-sort"></i>
</a>
</th>
<th class="Course_Type">
Description
<a ng-click="sort_by('Course_Type')">
<i class="icon-sort"></i>
</a>
</th>
<th class="cls">
Field 3
<a ng-click="sort_by('cls')">
<i class="icon-sort"></i>
</a>
</th>
<th class="SeatsAreAvailable">
Field 4
<a ng-click="sort_by('SeatsAreAvailable')">
<i class="icon-sort"></i>
</a>
</th>
<th class="StartDate">
Field 5
<a ng-click="sort_by('StartDate')">
<i class="icon-sort"></i>
</a>
</th>
</tr>
</thead>
<tfoot>
<td colspan="6">
<div class="pagination pull-right">
<ul>
<li ng-class="{disabled: currentPage == 0}">
<a href ng-click="prevPage()">« Prev</a>
</li>
<li
ng-click="setPage()"
ng-class="{active: n == currentPage}"
ng-repeat="n in range(pagedItems.length)"
>
<a href ng-bind="n + 1">1</a>
</li>
<li ng-class="{disabled: currentPage == pagedItems.length - 1}">
<a href ng-click="nextPage()">Next »</a>
</li>
</ul>
</div>
</td>
</tfoot>
<tbody>
<tr ng-repeat="item in pagedItems[currentPage] | orderBy:sortingOrder:reverse">
<td>{{item.LocName}}</td>
<td>{{item.Price}}</td>
<td>{{item.Course_Type}}</td>
<td>{{item.cls}}</td>
<td>{{item.SeatsAreAvailable}}</td>
<td>{{item.StartDate}}</td>
</tr>
</tbody>
</table>
</div>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://code.angularjs.org/1.1.5/angular.js"></script>
<script src="app.js"></script>
<script src="controllers.js"></script>
<script src="services.js"></script>
</body>
</html>
Still a better approach will be to use the ng-grid module.

Related

Angularjs Loop the record based on array

I am using Angular js
after hit I got response below response how to loop it
one div name then value like this i want to loop
my response
{
"my2":[
{
"id":5,
"cuid":20,
"name":"my2",
"month":"04",
"created_at":"2018-04-01 00:00:00",
"updated_at":"2018-04-11 00:00:00",
"time":"04:32 PM",
"status":"D"
},
{
"id":4,
"cuid":20,
"name":"my2",
"month":"04",
"created_at":"2018-04-02 00:00:00",
"updated_at":"2018-04-12 00:00:00",
"time":"12:10 PM",
"status":"P"
},
],
"my":[
{
"id":44,
"cuid":21,
"name":"my",
"month":"04",
"created_at":"2018-04-12 00:00:00",
"updated_at":"2018-04-12 00:00:00",
"time":"09:08 PM",
"status":"P"
}
],
"Testing":[
{
"id":43,
"cuid":19,
"name":"Testing",
"month":"04",
"created_at":"2018-04-12 00:00:00",
"updated_at":"2018-04-12 00:00:00",
"time":"09:05 PM",
"status":"P"
}
]
}
i try this
<div ng-repeat="data in reports" class="all_report">
<div ng-repeat="data in reports">
{{reports.indexOf(data)}}
</div>
<!--<div class="date">
{{data.created_at}} <br/>
<span class="month">{{data.created_at}}</span>
</div>
<div class="status">{{data.status}}</div>-->
</div>
but it not print anything how to print in div format
I don't know how to print
I tried above but not printing
how to achieve this to print in ng-repet?
You can use ng-repeat="(key, value) in reports" to iterate over the keys-value pairs in your reports object. For your specific case, the HTML would look something like the following:
<div ng-repeat="(key, value) in reports" class="all_report">
<div>{{key}}</div>
<div ng-repeat="data in value">
<div>{{$index}}</div>
<!-- Access data from the individual report rows here -->
</div>
</div>
look I can help you with your question, but it would be better if you write the answer you expect to see from JSON, to be able to accommodate HTML, but look at angularJS with ng-repeat helps you navigate the JSON, but as long as you have Well built the JSON, it suits you a bit the div, if it's really what you need.
I leave a link where you can support
https://jptacek.com/2013/10/angularjs-introducing-ng-repeat/
$scope.test = {
"my2":[
{
"id":5,
"cuid":20,
"name":"my2",
"month":"04",
"created_at":"2018-04-01 00:00:00",
"updated_at":"2018-04-11 00:00:00",
"time":"04:32 PM",
"status":"D"
},
{
"id":4,
"cuid":20,
"name":"my2",
"month":"04",
"created_at":"2018-04-02 00:00:00",
"updated_at":"2018-04-12 00:00:00",
"time":"12:10 PM",
"status":"P"
},
],
"my":[
{
"id":44,
"cuid":21,
"name":"my",
"month":"04",
"created_at":"2018-04-12 00:00:00",
"updated_at":"2018-04-12 00:00:00",
"time":"09:08 PM",
"status":"P"
}
],
"Testing":[
{
"id":43,
"cuid":19,
"name":"Testing",
"month":"04",
"created_at":"2018-04-12 00:00:00",
"updated_at":"2018-04-12 00:00:00",
"time":"09:05 PM",
"status":"P"
}
]
}
In HTML, something like that can go...
<div ng-repeat="data in test" class="all_report">
<div ng-repeat="x in data">
{{x}}
</div>
</div>

Get month from date in angularjs ng-repeat

I have an AngularJS 1.X app with a date field retrieved from a .json file. The date is being converted from a string to a date object to order the list but I need to capture the "month" part of the date to group by and for separate display but can't figure it out.
Here's my controller and HTML:
Angular Controller:
(function () {
"use strict";
angular.module("xxyyzz")
.controller("displayEventCtrl", displayEventCtrl);
function displayEventCtrl($http) {
var model = this;
model.header = "Upcoming Events";
model.events = [];
$http.get("/App/Data/eventCalendar.json")
.then(function (response) {
model.events = response.data;
console.log(model.events);
});
model.sortDate = function (event) {
var date = new Date(event.date);
return date;
}
}
})();
HTML:
<div ng-controller="displayEventCtrl as model">
<h3><i class="fa fa-calendar"></i> {{model.header}}</h3>
<div class="list-group">
<a href="#" class="list-group-item" ng-repeat="event in model.events | orderBy : -model.sortDate : true track by $index">
<div class="list-group-item-heading">
<h4>{{event.title}}</h4>
</div>
<p class="list-group-item-text">
Tuctus placerat scelerisque.
</p>
<div class="row">
<div class="col-xs-6">
<span class="small">{{event.location}}</span>
</div>
<div class="col-xs-6">
<span class="small pull-right">
{{event.startTime}} - {{event.endTime}}
</span>
</div>
</div>
<div class="row">
<div class="col-xs-9">
<span class="small">{{event.city}}, {{event.state}}</span>
</div>
<div class="col-xs-3">
<span class="small pull-right">{{event.date}}</span>
<div class="clearfix"></div>
</div>
</div>
</a>
</div>
</div>
JSON example:`
[
{
"id": 1,
"title": "Christmas Parade",
"date": "12/25/2017",
"city": "Dallas",
"state": "TX",
"location": "Galleria Mall",
"startTime": "11:00",
"endTime": "15:00"
},
{
"id": 2,
"title": "Thanksgiving Parade",
"date": "11/23/2017",
"city": "Denver",
"state": "CO",
"location": "Mile High Stadium",
"startTime": "11:00",
"endTime": "15:00"
},
{
"id": 3,
"title": "Halloween Parade",
"date": "10/31/2017",
"city": "Sleepy Hollow",
"state": "NY",
"location": "Ichabod Crane House",
"startTime": "19:00",
"endTime": "21:00"
},
{
"id": 4,
"title": "Independence Day Fireworks",
"date": "07/04/2017",
"city": "Washington",
"state": "DC",
"location": "National Mall",
"startTime": "11:00",
"endTime": "15:00"
}
]
Any help would be appreciated.
You can use js api named moment. Inject moment as dependency. You can use moment to get date in any formate you want.
moment ().get ('month');
To get the month, use the getMonth() function
var Xmas95 = new Date('December 25, 1995 23:15:30');
var month = Xmas95.getMonth();
console.log(month); // 11
My issue is that I am trying to pull the date from the array in the ng-repeat. So I can't declare the variable like above as it is part of a returned array {{event.date}}. What I need to know is how to get that date part from the nested item.
Use a custom filter to convert the text data to a Date object:
angular.module("app",[])
.filter("toDate", function() {
return function(data) {
return new Date(data);
};
})
.run(function($rootScope) {
var vm = $rootScope;
vm.Xmas95 = 'December 25, 1995 23:15:30';
})
<script src="//unpkg.com/angular/angular.js"></script>
<div ng-app="app">
Month number = {{Xmas95 | toDate | date: 'MM'}}
</div>
For more information, see
AngularJS Developer Guide - Creating Custom Filters
AngularJS date Filter API Reference

Filter unique value per key in angularjs and get checked

I have an angular object, i have to show its records with filter and sorting. Also i have to show the records of unique values per keys within the object with checkbox.
I shows record with filter and sorting also i showed the unique values per key with checkbox.
Now i have to get the values of these checkbox per key.
Here is my code with plunker url below.
index.html
<body ng-controller="myController">
<label ng-repeat="option in structure.tabs">
<input type="checkbox" ng-model="option.selected">{{option.index}}
</label>
<table border="1" width="100%">
<tr>
<th ng-repeat="header in structure.tabs" ng-show="header.selected" ng-click="sortData(header.filter)">{{header.index}}</th>
</tr>
<tr ng-repeat="data in structure.info | orderBy:sortColumn:reverseSort">
<td ng-show="structure.tabs[0].selected">{{data.name}}</td>
<td ng-show="structure.tabs[1].selected">{{data.age}}</td>
<td ng-show="structure.tabs[2].selected">{{data.city}}</td>
<td ng-show="structure.tabs[3].selected">{{data.designation}}</td>
</tr>
</table>
<h1>Unique Values Table (per key)</h1>
<table border="1" width="100%" style="margin-top: 50px;">
<tr>
<th ng-repeat="header1 in structure.tabs" ng-show="header1.selected">{{header1.index}}</th>
</tr>
<tr>
<td ng-repeat="(hk, hv) in structure.tabs" ng-show="hv.selected">
<table border='1'>
<tr ng-repeat="(dk, dv) in structure.info | unique:hv.filter">
<td>
<input type="checkbox">{{dv[hv.filter]}}
</td>
</tr>
</table>
<br>
<button ng-click="getChecked(hv.filter)">Get Checked</button>
</td>
</tr>
</table>
</body>
app.js
var app = angular.module('myApp', []);
app.controller("myController", function ($scope,$log) {
$scope.sortColumn="name";
$scope.reverseSort=false;
$scope.sortData=function(column) {
$scope.reverseSort=($scope.sortColumn==column) ? !$scope.reverseSort : false;
$scope.sortColumn=column;
}
$scope.structure={
"tabs": [
{
"index": "Name",
"filter": "name",
"selected": true
},
{
"index": "Age",
"filter": "age",
"selected": true
},
{
"index": "City",
"filter": "city",
"selected": true
},
{
"index": "Designation",
"filter": "designation",
"selected": true
}
],
"info": [
{
"name": "Abar",
"age": "27",
"city": "Ghaziabad",
"designation": "Php Developer"
},
{
"name": "Abar",
"age": "27",
"city": "Okhla",
"designation": "Html Developer"
},
{
"name": "Nishant",
"age": "25",
"city": "Delhi",
"designation": "Angular Developer"
},
{
"name": "Amit",
"age": "30",
"city": "Noida",
"designation": "Android Developer"
}
]
};
$scope.getChecked = function(tab) {
alert("Need to get all checked value of key: "+tab);
}
});
app.filter('unique', function() {
return function (arr, field) {
var o = {}, i, l = arr.length, r = [];
for(i=0; i<l;i+=1) {
o[arr[i][field]] = arr[i];
}
for(i in o) {
r.push(o[i]);
}
return r;
};
});
See in plunker http://embed.plnkr.co/wblXhejmSWApBeCAusaI/
You can do like below example:
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />'); </script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="script.js"></script>
</head>
<body ng-controller="myController">
<h1>Filter Table</h1>
<label ng-repeat="option in structure.tabs">
<input type="checkbox" ng-model="option.selected">{{option.index}}
</label>
<table border="1" width="100%">
<tr>
<th ng-repeat="header in structure.tabs" ng-show="header.selected" ng-click="sortData(header.filter)">{{header.index}}</th>
</tr>
<tr ng-repeat="data in structure.info | orderBy:sortColumn:reverseSort">
<td ng-show="structure.tabs[0].selected">{{data.name}}</td>
<td ng-show="structure.tabs[1].selected">{{data.age}}</td>
<td ng-show="structure.tabs[2].selected">{{data.city}}</td>
<td ng-show="structure.tabs[3].selected">{{data.designation}}</td>
</tr>
</table>
<h1>Unique Values Table (per key)</h1>
<table border="1" width="100%" style="margin-top: 50px;">
<tr>
<th ng-repeat="header1 in structure.tabs" ng-show="header1.selected">{{header1.index}}</th>
</tr>
<tr>
<td ng-repeat="(hk, hv) in structure.tabs" ng-show="hv.selected">
<table border='1'>
<tr ng-repeat="(dk, dv) in structure.info | unique:hv.filter">
<td>
<input ng-model="item" type="checkbox" ng-change="getCheckedValues(item,dv,hv.filter)">{{dv[hv.filter]}}
</td>
</tr>
</table>
<br>
<button ng-click="getChecked(hv.filter)">Get Checked</button>
</td>
</tr>
</table>
</body>
</html>
app.js
var app = angular.module('myApp', []);
app.controller("myController", function ($scope,$log) {
$scope.sortColumn="name";
$scope.reverseSort=false;
$scope.sortData=function(column) {
$scope.reverseSort=($scope.sortColumn==column) ? !$scope.reverseSort : false;
$scope.sortColumn=column;
}
var array = []
array["name"] = [];
array["age"] = [];
array["designation"] = [];
array["city"] = [];
$scope.getCheckedValues = function(e,val,key){
console.log(val)
if(e){
array[key].push(e)
}else{
array[key].shift()
}
}
$scope.structure={
"tabs": [
{
"index": "Name",
"filter": "name",
"selected": true
},
{
"index": "Age",
"filter": "age",
"selected": true
},
{
"index": "City",
"filter": "city",
"selected": true
},
{
"index": "Designation",
"filter": "designation",
"selected": true
}
],
"info": [
{
"name": "Abar",
"age": "27",
"city": "Ghaziabad",
"designation": "Php Developer"
},
{
"name": "Abar",
"age": "27",
"city": "Okhla",
"designation": "Html Developer"
},
{
"name": "Nishant",
"age": "25",
"city": "Delhi",
"designation": "Angular Developer"
},
{
"name": "Amit",
"age": "30",
"city": "Noida",
"designation": "Android Developer"
}
]
};
$scope.getChecked = function(tab) {
alert("Need to get all checked value of key: "+tab);
console.log(array[tab])
}
});
app.filter('unique', function() {
return function (arr, field) {
var o = {}, i, l = arr.length, r = [];
for(i=0; i<l;i+=1) {
o[arr[i][field]] = arr[i];
}
for(i in o) {
r.push(o[i]);
}
return r;
};
});
Alright. Apologies for my previous answer I completely botched the question.
Anyhow I spent almost an hour trying to solve this and managed to do it using $scope.$$watchers[0].last and underscorejs.
//this is how getChecked looks like now
$scope.getChecked = function(tab) {
var selectedKey = tab.$$watchers[0].last;
_.each($scope.structure.info,function(row){
_(row).pairs().filter(function(item){
_.each(item,function(key){
if(key===selectedKey)
{
console.log(row);
return;
}
})
})
})
Above method is responsible for identifying the key and spitting in console, each time you select a key in below table. So check console.
The solution is on below plunkr.
https://embed.plnkr.co/kbiCwhW0RrdHtO3hVEEk/

AngularJS : `Load more` button in each group of ng-repeat with many groups titles

I want to add load more button to the bottom of each group like the image here, and after clicking the button it shows rest of parts of the relevant group
where a,g are groups titles those have group property
In the snippet bellow, the code return only one load more button, and with no consideration of the group property.
var myApp = angular.module('myApp',[]);
myApp.controller('main', ['$scope', function($scope) {
$scope.test = "test";
$scope.filteredModules = [
{
"name":"a",
"group":"a"
},
{
"name":"b",
},
{
"name":"c",
},
{
"name":"c",
},
{
"name":"e",
},
{
"name":"f",
},
{
"name":"g",
"group":"g"
}
,{
"name":"h",
},
{
"name":"i",
},
{
"name":"j",
},
{
"name":"k",
}
,
{
"name":"l",
}
];
$scope.limit = 4;
$scope.loadMore = function() {
var increamented = $scope.limit + 4;
$scope.limit = increamented > $scope.filteredModules.length ? $scope.filteredModules.length : increamented;
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="main">
<div ng-repeat="node in filteredModules | limitTo:limit track by $index">
<div ng-if="!node.group">{{node.name}}</div>
<div ng-if="node.group" style="background-color:red">{{node.name}} </div>
</div>
<button ng-click="loadMore()">Load more</button>
</div>
</div>
Please try this snippet
var myApp = angular.module('myApp',[]);
myApp.controller('main', ['$scope', function($scope) {
$scope.filteredModules = {
"groups":
[
{
"title": "Alfreds Futterkiste",
"childs": ["child-1", "child-2", "child-3", "child-4", "child-5", "child-6","child-7", "child-8", "child-9"],
"limit": "3"
},
{
"title": "Ana Trujillo Emparedados y helados",
"childs": ["child-1", "child-2", "child-3", "child-4", "child-5", "child-6"],
"limit": "4"
},
{
"title": "Antonio Moreno Taquería",
"childs": ["child-1", "child-2", "child-3", "child-4", "child-5", "child-6"],
"limit": "3"
}
]
};
$scope.loadMore = function(index) {
$scope.filteredModules.groups[index].limit = parseInt($scope.filteredModules.groups[index].limit) + 3;
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="main">
<div ng-repeat="node in filteredModules.groups track by $index">
<div ng-if="node.title" style="background-color:red">{{node.title}}
</div>
<div ng-repeat="child in node.childs | limitTo: node.limit">
{{child}}
</div>
<br/>
<button ng-click="loadMore($index)" ng-hide="node.limit >= node.childs.length">Load more</button>
<br/><br/>
</div>
</div>
</div>

Injector moduler error in angularJs

I am getting "Uncaught Error: [$injector:modulerr]". Can anyone help me to solve this. My code is as follows..
<!DOCTYPE html>
<html>
<head>
<style>
body {
max-width: 32em;
margin: 1em auto 0;
}
img { width: 30px; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
// https://angular-ui.github.io/
// setup app and pass ui.bootstrap as dep
var myApp = angular.module("angularTypeahead", ["ui.bootstrap"]);
// define factory for data source
myApp.factory("States", function(){
var states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Dakota", "North Carolina", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"];
return states;
});
// setup controller and pass data source
myApp.controller("TypeaheadCtrl", function($scope, States) {
console.log("hello");
$scope.selected = undefined;
$scope.states = States;
});
</script>
</head>
<body>
<div ng-app="angularTypeahead">
<div class="container-fluid" ng-controller="TypeaheadCtrl">
<h2><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/15309/angular-logo.svg" alt="Angular.js Logo"> Angular.js Typeahead</h2>
<div class="form-group">
<label for="states">Search for US States</label>
<input name="states" id="states" type="text" placeholder="enter a state" ng-model="selected" typeahead="state for state in states | filter:$viewValue | limitTo:8" class="form-control">
</div>
<button class="btn btn-success" type="submit">Submit</button>
</div>
</div>
</body>
</html>
Am I did wrong anywhere? I got this code from codepen. It is running perfectly there. But Its is not running in my local

Resources