Recently, I've been delving into AgularJS and took on a practice exercise:
JS file:
function CustomersController() {
this.sortBy = 'name';
this.reverse = false;
this.customers= [{joined: '2000-12-02', name:'John', city:'Chandler', orderTotal: 9.9956}, {joined: '1965-01-25',name:'Zed', city:'Las Vegas', orderTotal: 19.99},{joined: '1944-06-15',name:'Tina', city:'New York', orderTotal:44.99}, {joined: '1995-03-28',name:'Dave', city:'Seattle', orderTotal:101.50}];
this.doSort = function(propName) {
this.sortBy = propName;
this.reverse = !this.reverse;
};
}
HTML file:
<!doctype html>
<html ng-app="customersApp">
<head>
<title>Iterating Over Data</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body ng-controller="CustomersController">
<h2>Customers</h2>
Filter: <input type="text" ng-model="customerFilter.name" />
<br /><br />
<table>
<tr>
<th ng-click="doSort('name')">Name</th>
<th ng-click="doSort('city')">City</th>
<th ng-click="doSort('orderTotal')">Order Total</th>
<th ng-click="doSort('joined')">Joined</th>
</tr>
<tr ng-repeat="cust in customers | filter:customerFilter | orderBy:sortBy:reverse">
<td>{{ cust.name }}</td>
<td>{{ cust.city }}</td>
<td>{{ cust.orderTotal | currency }}</td>
<td>{{ cust.joined | date }}</td>
</tr>
</table>
<br />
<span>Total customers: {{ customers.length }}</span>
<script src="angular.js"></script>
<script src="app/app.js"></script>
<script src="app/controllers/customersController.js"></script>
</body>
</html>
When I interact with the webpage, I'm able to sort the data by clicking on the table's headers. This led me to wonder about the role of "sortBy". Is it an inherent variable within $scope? I experimented with renaming it (e.g., "sortby") but observed that it only triggered reversal rather than sorting. If indeed built-in, where can I access the predefined functions of $scope? Your insights are greatly appreciated!