如何使用ng-click动态重新加载ng-repeat数据?

Ste*_*ell 9 angularjs angularjs-directive angularjs-ng-repeat

我有一个包含ng-repeat指令的页面.在ng-repeat当第一次加载页面,但我希望能够作品使用ng-click刷新的内容ng-repeat.我尝试了以下代码,但它不起作用.有什么建议?

<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>
Run Code Online (Sandbox Code Playgroud)

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;
    });
};
Run Code Online (Sandbox Code Playgroud)

我希望我的调用loadItems()会导致ng-repeat指令重新加载从我的服务器获得的新数据.

Dan*_*nze 10

在回调中添加广播并在控制器中订阅它.

这真的应该是服务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;
    });
}; 
Run Code Online (Sandbox Code Playgroud)

在你的控制器中:

$scope.$on("updateItems",function(d){
  $scope.items = d;
});
Run Code Online (Sandbox Code Playgroud)

所以每当你 ng-click="update(id)"

$scope.update = function(id){
    itemsService.loadItems(id);
}
Run Code Online (Sandbox Code Playgroud)

items将自动更新,因为它已订阅.