AngularJS call

Sorry if that sounds stupid.

I have a problem similar to this question , and while the accepted answer worked, it also caused another problem: when I add a new object to the array, Angular does not display 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)
        })
    }

Is there anything I can do about this?

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)
      })
    }
  ]
+4
source share
2 answers

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

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

then call the method addPostinside 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')
        })

    }
])
+4
source

angular . push splice, .

, array .

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.
    })
}
+4

Source: https://habr.com/ru/post/1676702/


All Articles