Search code examples
angularjsangularjs-orderby

Angular orderBy not reordering on array push


When I push a new item to the array it's adding it to the end no matter what the bpm is. Once I refresh the page everything sorts properly.

//view
<form ng-submit="add(newSong)">
  <input ng-model="newSong.artist" placeholder="Artist..">
  <input ng-model="newSong.title" placeholder="Title..">
  <input ng-model="newSong.bpm" placeholder="BPM..">
  <input ng-model="newSong.key" placeholder="Key..">
  <input ng-model="newSong.year" placeholder="Year..">
  <button ng-show=''></button>
</form>

<div ng-repeat="song in songs | orderBy:'bpm'">
  {{song.bpm}} / {{song.artist}} - {{song.title}}
</div>

//controller
$http.get('/api/songs').success(function(data) {
    $scope.songs = data
})

$scope.add = function(newSong) {

    var song = {
        artist: newSong.artist
      , title: newSong.title
      , bpm: newSong.bpm
      , key: newSong.key
      , year: newSong.year
    }

    $scope.songs.push(song)

    $http.post('/api/songs', song).success(function(data) {
        console.log(data)
    })

}

When I wrote this in plunker it worked properly, I can't tell what's wrong with my environment (v1.2.25)


Solution

  • My model uses a Number for BPM. This fixed my problem:

    var song = {
            artist: newSong.artist
          , title: newSong.title
          , bpm: parseInt(newSong.bpm)
          , key: newSong.key
          , year: newSong.year
        }