I know various variations of this have been asked multiple times before, but nevertheless I am having trouble with it. I have a small angular app wherein I am comparing two characters (it's a D&D initiative roll). I am looking to sort the ng-repeat in the following code:
var dmTools = angular.module('dmTools', []);
dmTools.controller('initTracker', function($scope, $http) {
var charInit = function() {
this.name = "";
this.mod = 0;
this.init = 0;
}
$scope.characters = [
];
$scope.character = new charInit();
$scope.addChar = function() {
$scope.characters.push($scope.character);
$scope.character = new charInit();
}
$scope.deleteChar = function(character) {
$scope.characters.splice($scope.characters.indexOf(character), 1);
}
$scope.charSort = function(a, b) {
//first we go by initiative roll
if (a.init < b.init) {
return -1;
}
if (a.init > b.init) {
return 1;
}
//if initiative rolls are the same, go by initiative mod
if (a.mod < b.mod) {
return -1;
}
if (a.mod > b.mod) {
return 1;
}
//if both are the same, roll off until one gets a higher roll than the other.
var aRoll = 0;
var bRoll = 0;
while (aRoll == bRoll) {
aRoll = Math.floor(Math.random() * 20) + 1;
bRoll = Math.floor(Math.random() * 20) + 1;
if (aRoll < bRoll) {
return -1;
}
if (aRoll > bRoll) {
return 1;
}
}
//while this should not be possible to reach, we'll put it in for safeties sake.
return 0;
};
$scope.rollInit = function() {
for (x in $scope.characters) {
$scope.characters[x].init = Math.floor(Math.random() * 20) + 1 + $scope.characters[x].mod;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="app" id="initTracker" data-ng-controller="initTracker">
<h3>Initiative Tracker</h3>
<div class="form-group">
<label>Name
<input type="text" data-ng-model="character.name" class="form-control" />
</label>
</div>
<div class="form-group">
<label>Mod
<input type="number" data-ng-model="character.mod" class="form-control" />
</label>
</div>
<div>
<input class="btn btn-primary" style="margin:5px;" data-ng-click="addChar()" type="button" value="Add Character" />
<input class="btn btn-success" style="margin:5px;" data-ng-click="rollInit()" type="button" value="Roll Initiative" />
</div>
<table class="table table-striped">
<tr>
<th>Name</th>
<th>Modifier</th>
<th>Initiative</th>
<th>Delete</th>
</tr>
<tr data-ng-repeat="character in characters | orderBy: charSort">
<td data-ng-bind="character.name"></td>
<td data-ng-bind="character.mod"></td>
<td data-ng-bind="character.init"></td>
<td>
<input type="button" class="btn btn-danger" value="Delete" data-ng-click="deleteChar(character)" />
</td>
</tr>
</table>
</div>
My charSort function is a working sort that could easily be passed to an array.sort(function) sort of call, but angular is only passing in 1 character object to the function. How can I get a proper custom comparison based sort of this variety in an angular template?