How can I use ng-click to dynamically reload ng-repeat data?

陌路散爱 提交于 2019-12-20 20:27:13

问题


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;
    });
};

I was hoping that my call to loadItems() would cause the ng-repeat directive to reload with the new data obtained from my server.


回答1:


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.



来源:https://stackoverflow.com/questions/17816367/how-can-i-use-ng-click-to-dynamically-reload-ng-repeat-data

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