如何使用 ng-click 动态重新加载 ng-repeat 数据? [英] How can I use ng-click to dynamically reload ng-repeat data?
问题描述
我有一个包含 ng-repeat
指令的页面.ng-repeat
在页面首次加载时工作,但我希望能够使用 ng-click
刷新 ng-repeat的内容代码>.我已经尝试了以下代码,但它不起作用.有什么建议吗?
I have a page that contains an ng-repeat
directive. The ng-repeat
works when the page first loads, but I want to be able to use ng-click
to refresh the contents of the ng-repeat
. I have tried the following code but it doesn't work. Any suggestions?
<div ng-click="loadItems('1')">Load 1st set of items</div>
<div ng-click="loadItems('2')">Load 2nd set of items</div>
...
<table>
<tr ng-repeat="item in items">>
// stuff
</tr>
</table>
ItemsCtrl:
$scope.loadItems = function (setID) {
$http({
url: 'get-items/'+setID,
method: "POST"
})
.success(function (data, status, headers, config) {
$scope.items = data;
})
.error(function (data, status, headers, config) {
$scope.status = status;
});
};
我希望我对 loadItems()
的调用会导致 ng-repeat
指令重新加载从我的服务器获得的新数据.
I was hoping that my call to loadItems()
would cause the ng-repeat
directive to reload with the new data obtained from my server.
推荐答案
在您的回调中添加广播并在您的控制器中订阅它.
Add a broadcast in your callback and subscribe to it in your controller.
顺便说一句,这真的应该在服务中
itemsService.loadItems = function (setID) {
$http({
url: 'get-items/'+setID,
method: "POST"
})
.success(function (data, status, headers, config) {
$scope.items = data;
$rootScope.$broadcast('updateItems', data);
})
.error(function (data, status, headers, config) {
$scope.status = status;
});
};
在您的控制器中:
$scope.$on("updateItems",function(d){
$scope.items = d;
});
所以每当你 ng-click="update(id)"
$scope.update = function(id){
itemsService.loadItems(id);
}
您的 items
将自动更新,因为它已被订阅.
Your items
will automatically update because it is subscribed.
这篇关于如何使用 ng-click 动态重新加载 ng-repeat 数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!