9

我有一个包含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>

项目控制:

$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指令重新加载从我的服务器获得的新数据。

4

1 回答 1

10

在您的回调中添加广播并在您的控制器中订阅它。

顺便说一句,这真的应该在服务中

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遗嘱会自动更新,因为它已被订阅。

于 2013-07-23T17:02:46.597 回答