2017-05-09 68 views
4

對不起,如果這聽起來很愚蠢。AngularJS orderBy問題

我遇到類似於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) 
     }) 
    } 
    ] 

回答

4
在工廠

只返回HTTP,而不是展開承諾的工廠內

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

然後調用內部的addPost方法並承諾在承諾內承諾。

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

    } 
]) 
+0

好主意。儘管存在小問題,但您必須將promise中的'data.data'推入'$ scope.posts'中。我希望過濾器只在視圖初始化時才起作用。 –

4

實例角僅觸發改變。如果您只是通過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. 
    }) 
} 
+0

我希望過濾器只在視圖初始化時工作,而不是在後續添加時工作。這就是爲什麼我不使用ng-repeat中的orderBy:D。謝謝,現在就開始工作吧! –