带分页的角度嵌套ng重复范围



我正在使用带有材料库的角度。在项目中,我有两个带有 md 表的 ng-repeat 嵌套循环。问题是在嵌套循环中,变量每次在每个请求上都是 ovveriden。我可以提出一个请求并进行迭代,但我有动态分页,它不起作用。

这是带有表格的索引文件:

<div ng-init="getCategories()" flex>
...
<div class="content-main"  ng-repeat="category in categories">
...
<md-content>
<table md-table ng-init="getBooks(category.id)">
...
<tr md-row ng-repeat="book in books | orderBy: query.order ">
<td md-cell>
<span>{{ book.title }}</span>
</td>
...
</md-content>
<md-table-pagination md-limit="query.limit"
md-limit-options="limit"
md-page="query.page"
md-page-select="options.pageSelect"
md-total="{{booksCount}}"
md-boundary-links="options.boundaryLinks">
</md-table-pagination>

简化的角度控制器功能:

$scope.getCategories = function () {
\get request
$scope.categories = resp.data.rows;
}
$scope.getBooks = function () {
\get request with pagination and search params
$scope.books = resp.data.rows;
$scope.booksCount = resp.data.amount;
}

所以每个请求 getBooks ovverides "books" 变量,现在例如我有两个类别 abd,我看到两个类别的相同书籍(来自类别 2)。

Category 1
Book C Book D
Category 2 
Book C Book D
(wrong)

但是我还有一类书:

Category 1
Book A Book B
Category 2 
Book C Book D
(correct)

您面临此问题是因为您的ng-repeat中有一个ng-init,它为每个迭代设置$scope.books,其中最后一个迭代最终覆盖了所有以前的$scope.books实例。

我建议对您的代码进行以下更改:

  • 与其在ng-repeat中使用ng-init,不如直接从getCategories中的成功回调调用getBooks。不鼓励使用ng-init,也被认为是不好的做法。所以,像这样:

    $scope.getBooks = function (categoryId) {
    // get request with pagination and search params
    $scope.books[categoryId] = resp.data.rows;
    $scope.booksCount[categoryId] = resp.data.amount;
    }
    $scope.getCategories = function () {
    //get request
    $scope.categories = resp.data.rows;
    $scope.books = {};
    $scope.booksCount = {};
    $scope.categories.forEach(function(category) {
    $scope.getBooks(category.id)
    })
    }
    $scope.getCategories();
    
  • 现在你的 HTML 将如下所示:

    <div flex>
    ...
    <div class="content-main" ng-repeat="category in categories">
    ...
    <md-content>
    <table md-table>
    ...
    <tr md-row ng-repeat="book in books[category.id] | orderBy: query.order">
    <td md-cell>
    <span>{{ book.title }}</span>
    </td>
    ...
    </md-content>
    

这应该工作正常..除非它有任何愚蠢的错误,因为没有提供可验证的示例

你应该先像这样改变你的控制器:

$scope.getCategories = function () {
//get request
$scope.categories = resp.data.rows;
angular.forEach($scope.categories, function (category, index) {
$scope.getBooks(category);
});
}();
$scope.getBooks = function(category) {
// make request by passing category.id.
//get request with pagination and search params
$scope.category = resp.data;
};

你的HTML将看起来像:

<div flex>
...
<div class="content-main"  ng-repeat="category in categories">
...
<md-content>
<table md-table>
...
<tr md-row ng-repeat="book in category.rows | orderBy: query.order ">
<td md-cell>
<span>{{ book.title }}</span>
</td>
...
</md-content>

最新更新