我需要一些帮助来显示来自$ watch
的ng-repeat指令中的更新结果我错过了什么吗?
谢谢。
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>
答案 0 :(得分:1)
如果其他人碰到这个或有人可以解释原因 - 答案是将整个表元素封装在控制器中而不仅仅是ng-repeat
<强>解决方案:强>
<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>
答案 1 :(得分:0)
所以看起来console.log(retProducts);
会打印新值,但屏幕不会刷新。我认为这是因为您的复制代码是$ apply,因此复制后没有$ digest。我会将你的angular.copy包装在$ apply:
.factory('ProductService', ['Product', '$rootScope', function(Product){
var products = [];
function updateProducts(productType){
console.log("ProductService updateProducts with product type " + productType);
Product.query({product_type: productType},
function (data) {$rootScope.$apply(function() {
console.log("ProductService updateProducts returned " + data);
var retProducts = data;
angular.copy(retProducts, products);
//console.log(retProducts);
})});
}
return {
products: products,
updateProducts: updateProducts
}}])