控制器:
function ProductListCtrl($scope, Product) {
$scope.page = 1;
$scope.setPage = function(page) {
$scope.page = page;
}
Product.query({page:$scope.page}, function(response) {
$scope.products = response.records;
$scope.product_count = response.metadata.count;
$scope.page_count = response.metadata.page_count;
});
}
查看:
<div class="container-fluid">
<div class="row-fluid">
<div class="span2">
<!--Sidebar content-->
Search: <input ng-model="query">
</div>
<div class="span10">
<!--Body content-->
Number of products: {{product_count}}.<br>
Page {{page}} of {{page_count}}.
<ul class="products">
<li ng-repeat="product in products | filter:query | orderBy:orderProp" class="thumbnail">
<a href="#/products/{{product.id}}" class="thumb"><img ng-src="{{product.imageUrl}}"></a>
<a href="#/products/{{product.id}}">{{product.name}}</a>
<span ng-repeat="category in product.categories">{{category.name}}</span>
</li>
</ul>
<a href="#" ng-class="{disabled: page < 2}" ng-click="setPage(page-1)">Previous page</a>
<a href="#" ng-class="{disabled: page == page_count}" ng-click="setPage(page+1)">Next page</a>
</div>
</div>
</div>
单击“下一页”链接,使用正确的页码(即下一页)调用setPage
函数,但页面变量未在视图中更新。该列表从后端重新加载,但使用原始页码。
我做错了什么?
答案 0 :(得分:0)
您可能需要调用$ scope。$ apply()
答案 1 :(得分:0)
我认为你的观点周围有<div ng-controller="ProductListCtrl">
这样的东西?
此外,Product.query
只会被调用一次,因此如果您需要再次查询服务器,可以将其包装到一个函数中,并在用户点击时在setPage
中调用它,即:
var updateProducts = function() {
Product.query({page:$scope.page}, function(response) {
$scope.products = response.records;
$scope.product_count = response.metadata.count;
$scope.page_count = response.metadata.page_count;
});
}
updateProducts(); // call it once when the controller is initialised
$scope.setPage = function(page) {
$scope.page = page;
updateProducts(); // call it again after the user clicks
}
设置$scope.page
不会触发Product.query
本身,因此您必须自己调用它。