Get correct index with Splice()

风流意气都作罢 提交于 2019-12-11 10:48:02

问题


I'm attempting to delete items from my AngularJS view. From the view, I'm passing the index & the ID. In the JS controller, I splice(index) from the AngularJS array/model. And I pass the ID to a $http.get to call a delete to my database. This all works.

....

Until I make a request to refresh my page. Every 5 seconds I make a request to update the Angular model and I concat any new data to it. But what I'm finding is it screws up my index values. I assumed it was reordering my index: and reading this StackOverflow thread helped confirm that.

What would happen is that I push delete for the 3rd item on the page, and it deletes that ID from the DB. But it splices the wrong item from the page until I refresh the page. How do I make sure that I'm always passing the correct index?

View

<li ng-repeat="new in news | filter:query | orderBy:orderProp">
     <div class="newsitem" id="newspost{{new.id}}">
         <h4 ng-model="news.title">{{new.title}} </h4>
         <p ng-model="news.text">{{new.text}}</p>
         <a class="btn btn-info" ng-click="visible = true">View article</a>
         <a ng-click="deleteNews(index,new.id)" class="btn btn-danger btn-mini">Delete</a>
     </div>
</li>

controllers.js

$scope.deleteNews = function(index, id) {
    $http.get('/ci/index.php/news/delete_news_ajax/'+id).success(function(){
        $scope.news.splice(index, 1);
    });
};

回答1:


Instead of passing the index and id, pass new:

<a ng-click="deleteNews(new)" ...>

Then use indexOf in your controller function:

$scope.deleteNews = function(newsItem) {
   $http.get('/ci/index.php/news/delete_news_ajax/' + newsItem.id)).success(function() {
      $scope.news.splice($scope.news.indexOf(newsItem), 1);
   });
}


来源:https://stackoverflow.com/questions/15510215/get-correct-index-with-splice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!