orderBy number angular js

I have an array of objects...

var userObjects =[
{userName: bob,
 age: "25",
 gender: "m"
},
{userName: bill,
 age: "15",
 gender: "m"
},
{userName: jen,
 age: "45",
 gender: "f"
},
]

Now I have an ng-repeat in my HTML to iterate over this array of objects. I want it to sort the age:

<tr ng-repeat="user in userObjects | orderBy:-age">

In my JS I am converting my ages to intergers....

data.forEach(function(user){
   user.age= parseFloat(user.age);
}

Angular will not sort by age, I would expect to see...

bill, 15
bob, 25
jen, 45

But instead they are all over the place. What am I doing wrong?

Thanks!

Answers


Try wrapping -age in single quotes, like '-age'


Not necessary to convert strings to numbers in JS.

Make it in pure Angular with filter:

| orderBy:'-1*age'`


Following will convert the 'age' into numeric and sort in ascending order.

| orderBy : 'age/1'


Try this dude.....

ng-repeat="user in userObjects | orderBy:'age'">


angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        {name:'Jani',age:'18'},
        {name:'Carl',age:'32'},
        {name:'Margareth',age:'21'},
        {name:'Hege',age:'14'},
        {name:'Joe',age:'36'},
        {name:'Gustav',age:'42'},
        {name:'Birgit',age:'28'},
        {name:'Mary',age:'58'},
        {name:'Kai',age:'26'}
        ];
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="namesCtrl">

<p>Looping with objects:</p>
<ul>
  <li ng-repeat="x in names | orderBy:'age'">
    {{ x.name + '-' + x.age }}
  </li>
</ul>

</div>

</body>
</html>

Ascending order:-

<div ng-repeat="person in persons | orderBy:'age'">

Descending order:-

<div ng-repeat="person in persons | orderBy:'-age'">

Need Your Help

Convert a list of strings into one string

python string list

I'm super new to any sort of programming, so forgive my ignorance for not knowing how to do something that seems so simple.

iPhone view navigation problem

iphone transactions uiviewcontroller

i've a 3 views based app. To navigate from different views i use the delegate method, for example in the second view i've a delegate which is the reference to the first view and when i want to pass...