gpt4 book ai didi

javascript - 使用新数据重新加载 ng-repeat

转载 作者:行者123 更新时间:2023-12-02 16:56:07 25 4
gpt4 key购买 nike

我有一项服务,我只需返回一个包含所有可用视频的列表,然后将其注入(inject)到 Controller 中,这样我就可以执行 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?或者说有什么更好的办法吗?

最佳答案

尝试如下:

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">

它还添加了许多其他不错的功能;)

关于javascript - 使用新数据重新加载 ng-repeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26158681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com