2013-05-26 164 views
0

控制器:角 - 範圍變量不正確更新

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

我覺得你需要在更改頁面時重新查詢(),不是嗎? – Ven

回答

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,所以您必須自己調用它。