我正在使用带有材质lib的角度。在项目中,我有两个嵌套的ng-repeat循环和md-tables。问题是在嵌套循环中,每次请求时变量都是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)
但我有第1类另一本书:
Category 1
Book A Book B
Category 2
Book C Book D
(correct)
答案 0 :(得分:2)
您遇到此问题是因为ng-init
内有ng-repeat
,每次迭代设置$scope.books
,最后一次迭代会覆盖$scope.books
的所有先前实例。
我建议您对代码进行以下更改:
不要在ng-init
内使用ng-repeat
,而是直接从getBooks
内的成功回调中调用getCategories
。不鼓励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>
这应该工作正常..除非它有任何愚蠢的错误,因为没有提供可验证的示例
答案 1 :(得分:1)
您应该首先更改控制器:
$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>