How can I use ng-click to dynamically reload ng-repeat data?
12,926
Add a broadcast in your callback and subscribe to it in your controller.
This should really be in a service btw
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;
});
};
In your controller:
$scope.$on("updateItems",function(d){
$scope.items = d;
});
So whenever you ng-click="update(id)"
$scope.update = function(id){
itemsService.loadItems(id);
}
Your items
will automatically update because it is subscribed.
Author by
Stephanie Caldwell
Updated on July 25, 2022Comments
-
Stephanie Caldwell almost 2 years
I have a page that contains an
ng-repeat
directive. Theng-repeat
works when the page first loads, but I want to be able to useng-click
to refresh the contents of theng-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; }); };
I was hoping that my call to
loadItems()
would cause theng-repeat
directive to reload with the new data obtained from my server. -
Stephanie Caldwell almost 11 yearsWhere do I place the
itemsService.loadItems =
block of code? Does it go in a module? -
Dan Kanze almost 11 years@StephanieCaldwell It's a style of declaring an object in a service. Look into service functions.
-
Parth about 9 yearsWill any one please provide working jsfiddle or Demo for the same?