我有一项服务,我只返回一个包含所有可用视频的列表,然后将其注入控制器,这样我就可以ng-repeat
列出这些视频。就像这样
videosApp.factory('VideosService', function ($http, $rootScope) {
$rootScope.videos = {
list: [],
};
$http.get('/panel/videos')
.then(
function (response) {
$rootScope.videos.list = response.data;
},
function () {
alert('what is the velocity of a swallow?');
}
);
return $rootScope;
});
videosApp.controller('VideosController', [
'$scope', '$http', '$filter', '$window',
function ($scope, $http, VideosService) {
$scope.deleteVideo = function(id) {
if (confirm('Are you sure you want to delete this video?')) {
$http.delete('/panel/videos/'+id)
.then(
function (response) {
growl(response.data.message, 'success');
},
function (response) {
growl(response.data.message, 'danger');
}
);
}
}
}
]);
现在,对于HTML输出:
<div id="videos-listing" class="row" ng-controller="VideosController">
<ul>
<li ng-repeat="video in videos.list">
{{video.name}}
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
<li role="presentation">
<a role="menuitem" href="#delete" ng-click="deleteVideo(video.id)">Delete</a>
</li>
</ul>
</li>
</ul>
</div>
现在,正如您所看到的,还有一个Delete
函数,它可以完美地运行。我的问题是,在删除特定项目后,如何刷新该列表。
我将get /panel/videos
包裹在一个函数中,并在删除成功后再次调用它,但是,如何刷新该ng-repeat?或者,有没有更好的方法呢?
答案 0 :(得分:2)
尝试类似:
<强> HTML 强>
<a role="menuitem" href="#delete" ng-click="deleteVideo(video)">Delete</a>
<强> JS 强>
$scope.deleteVideo = function(video) {
if (confirm('Are you sure you want to delete this video?')) {
$http.delete('/panel/videos/'+video.id)
.then(
function (response) {
growl(response.data.message, 'success');
$scope.videos.list.splice($scope.videos.list.indexOf(video),1);
},
function (response) {
growl(response.data.message, 'danger');
}
);
}
}
<强>更新强>
此外,您可以考虑使用一些收集助手,例如Backbone's Collections
您的代码看起来像那样,然后:
JS:
$rootScope.videos.list = new Backbone.Collection();
$rootScope.videos.list.reset(response.data);
...
$scope.videos.list.remove(video);
HTML
<li ng-repeat="video in videos.list.models">
它还增加了许多其他不错的功能;)