【问题标题】:AngularJS orderBy issueAngularJS orderBy 问题
【发布时间】:2017-05-09 12:06:31
【问题描述】:

对不起,如果这听起来很愚蠢。

我遇到了类似于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)
      })
    }
  ]

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    在工厂中只返回 http 而不是在工厂内解开承诺

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

    【讨论】:

    • 好主意。虽然有一个小问题,但你必须将 Promise 中的 data.data 推送到 $scope.posts 中。我希望过滤器仅在视图初始化时才起作用。
    【解决方案2】:

    角度仅触发实例更改。如果您只是通过pushsplice 修改数组,则不会触发过滤器。

    您可以通过以下方式为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.
        })
    }
    

    【讨论】:

    • 我希望过滤器仅在视图初始化时工作,而不是在后续添加时工作。这就是为什么我不在 ng-repeat 中使用 orderBy 的原因:D。谢谢,现在可以使用了!
    猜你喜欢
    • 2014-09-05
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多