Search code examples
angularjsangularjs-scopeangularjs-ng-repeatangularjs-serviceangularjs-controller

ng-repeat not updating using $scope.$watch


I need some help in displaying the results of an update in my ng-repeat directive from $watch

  • ProductsCtrl is watching for a change of product type and when it detects one it searches for Products of that type.
  • This definitely detects the product type change and I'm getting results back from the updateProducts function but the products I get back are not displayed.
  • I thought mapping the $scope.productService.products to ProductService.products would mean it would be updated automatically.

Am I missing something?

Thank you.

controllers.js

.controller('ProductsCtrl',['$scope','ProductService', '$location', 'SessionDataService',    function($scope, ProductService, $location, SessionDataService){

  $scope.productService = ProductService;
  $scope.productService.products = ProductService.products;
  $scope.sessionDataService = SessionDataService;
  $scope.productType = SessionDataService.productType;

  $scope.$watch('productType', function(productTypeNew, productTypeOld){
      //update products
        console.log('ProductsCtrl: watch : New Val - '+ productTypeNew + ',     Old Val - ' + productTypeOld);
        $scope.productService.updateProducts(productTypeNew);
        console.log("ProductsCtrl: watch : Products retrieved - " +         $scope.productService.products);        
}, true);

}]);   

services.js

.factory('Product',['$resource', function($resource){
return $resource('/products/:id', {
    id: '@id'
});
}])
.factory('ProductService', ['Product', function(Product){
var products = [];

function updateProducts(productType){
    console.log("ProductService updateProducts with product type " + productType);
        Product.query({product_type: productType},
        function (data) {
            console.log("ProductService updateProducts returned " + data);
              var retProducts = data;
              angular.copy(retProducts, products);
              //console.log(retProducts);
            });
}
return {

    products: products,
    updateProducts: updateProducts

}}])

html

<div ng-controller="ProductsCtrl">
        <tr ng-repeat="product in productService.products">
            <td>{{product.title}}</td>
            <td>{{product.retailler}}</td>
        </tr>
    </div>

Solution

  • In case someone else runs into this or someone can explain why - the answer was to encapsulate the whole table element in the controller and not just the ng-repeat

    Solution:

    <div ng-controller="ProductsCtrl">
        <table>
            <tr>
                <th>Product</th>
                <th>Retailler</th>
            </tr>
    
            <tr ng-repeat="product in products">
                <td>{{product.title}}</td>
                <td>{{product.retailler}}</td>
            </tr>
        </table>
        </div>