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

时间:2021-08-05 20:32:20

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?

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

ItemsCtrl:

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.

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

1 个解决方案

#1


10  

Add a broadcast in your callback and subscribe to it in your controller.

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

This should really be in a service btw

这真的应该是服务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)"

所以无论何时你ng-click =“update(id)”

$scope.update = function(id){
    itemsService.loadItems(id);
}

Your items will automatically update because it is subscribed.

您的商品会因订阅而自动更新。

#1


10  

Add a broadcast in your callback and subscribe to it in your controller.

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

This should really be in a service btw

这真的应该是服务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)"

所以无论何时你ng-click =“update(id)”

$scope.update = function(id){
    itemsService.loadItems(id);
}

Your items will automatically update because it is subscribed.

您的商品会因订阅而自动更新。