While working with the MEAN stack and jade, I encountered an issue with AngularJS when using ng-repeat, ng-click, and orderby to sort columns in a table. Everything was working well until I tried sorting by a column named "To Do" which contains a space. This led to a syntax error in Chrome when trying to order by that specific column.
Despite finding some similar posts about handling properties with spaces, none of the solutions seem to work for me.
Jade: (Here is how I have set up ng-click, orderBy, and ng-repeat in Jade)
table
caption {{collectionName}}
thead
tr
th(ng-repeat="column in columns" ng-click="setPredicate(column);")
{{column}}
tbody
tr(ng-repeat="row in rows | orderBy:predicate:reverse")
td(ng-repeat="column in columns")
{{row[column]}}
Controllers.JS: (This is where data for columns and rows is received in Angular and orderBy predicate changes happen)
$http.get('/api/collection/' + $routeParams.collectionName)
.success(function(data){
$scope.collection = data;
$scope.columns = data.columns;
$scope.rows = data.rows;
console.log(data);
});
$scope.setPredicate = function(column){
if (column === "To Do"){
var keys = Object.keys($scope.rows[0])
$scope.predicate = keys[1];
// $scope.predicate = "To Do";
// $scope.predicate = column[$scope.columns];
}else{
$scope.predicate = column;
}
$scope.reverse = !$scope.reverse;
}
NodeJS index.JS: (How columns array and rows are sent to Angular from MongoDB)
router.get('/api/collection/:collectionName', function(req, res){
collectionProvider.findCollection(req.param('collectionName'), function(error, documents){
var keys;
if(documents[0]){
keys = Object.keys(documents[0]);
remove(keys,'_id');
}
res.json({
columns: keys,
title: req.param('collectionName'),
rows:documents,
collectionName: req.param('collectionName')
});
});
});
In summary, each column header in my table corresponds to a property representing the data in that column. Node dynamically retrieves all the properties of the first record and sends an array of property names to $scope.columns in Angular. When a column heading is clicked, a predicate switches the orderBy sorting accordingly.
This being my initial experience with angular, I had expected to directly use ng-click="predicate=column" in Jade but had to resort to sending it to a controller function instead. I am unsure if this approach aligns with best practices in Angular development.