Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS orderBy issue

Sorry if this sounds dumb.

I'm having a problem similar to this question and while the accepted answer worked, it also brought up another issue: When I add a new object to the array, Angular doesn't render it.

  app.controller('MainCtrl', [
    '$scope',
    '$filter',
    'posts',
    function($scope, $filter, posts) {
      $scope.posts = $filter('orderBy')(posts.posts, '-votes')
    }
  ]

My add function:

    o.addPost = function(post) {
        return $http.post('/posts', post).success(function(data) {
          o.posts.push(data)
        })
    }

Are there anything I can do about it?

EDIT: I'm going with this:

  o.addPost = function(post) {
      return $http.post('/posts', post)
  }

  app.controller('MainCtrl', [
    '$scope',
    '$filter',
    'posts',
    function($scope, $filter, posts) {
      $scope.posts = $filter('orderBy')(posts.posts, '-votes')

      $scope.addPost = function() {
        posts.addPost(param).then(function(response) {
        $scope.posts.push(response.data)
      })
    }
  ]
like image 632
Kise Avatar asked Feb 04 '23 11:02

Kise


2 Answers

in the factory just return the http instead of the unwrapping the promise inside the factory

o.addPost = function(post) {
    return $http.post('/posts', post);
}

then call the addPost method inside the factory.And catch the promise inside the promise.

app.controller('MainCtrl', [
    '$scope',
    '$filter',
    'posts',
    function($scope, $filter, posts) {
        var params = {};
        posts.addPost(params).then(function(data) {
            $scope.posts = $filter('orderBy')(data, '-votes')
        })

    }
])
like image 131
Sachila Ranawaka Avatar answered Feb 07 '23 11:02

Sachila Ranawaka


angular only trigger for instance changes. If you just modify the array by push or splice, the filter won't be fired.

you can do the following way to give the array a new instance.

o.addPost = function(post) {
    return $http.post('/posts', post).success(function(data) {
      o.posts.push(data);
      o.posts = o.posts.slice();    // this will give array a new instance and fire the filter.
    })
}
like image 22
Pengyy Avatar answered Feb 07 '23 12:02

Pengyy