javascript - AngularJS orderBy 问题

标签 javascript angularjs

抱歉,如果这听起来很蠢。

我遇到了类似于 this question 的问题虽然接受的答案有效,但它也带来了另一个问题:当我向数组添加一个新对象时,Angular 不会呈现它。

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

我的添加函数:

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

我能做些什么吗?

编辑:我要这样做:

  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)
      })
    }
  ]

最佳答案

在工厂中只返回 http 而不是在工厂内展开 promise

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

然后在工厂内部调用addPost方法,并在promise中捕获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')
        })

    }
])

关于javascript - AngularJS orderBy 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43860590/

相关文章:

javascript - Algolia 重复

javascript - 使用 jQuery 在单击的按钮上方添加内容时防止页面移动

javascript - 如何使用 React Native 访问对象的属性?

javascript - 使用 Angular 登录谷歌

javascript - 在其他情况下如何忽略循环

javascript - 可靠的 Angular 下拉菜单

javascript - AngularJS - 为什么选择下拉菜单没有 $event on change

javascript - 使用react-router-dom重定向react中的onclick事件

angularjs - 如何始终启用 Angular 可编辑的编辑状态

javascript - 使用 ng-repeat 创建 AngularJS 表