'AngularJS $watch isn't being fired when watch variable is updated
I have a list of products on my ProductsController that I'm trying to update with a $watch. However, productsService.products watch only fires on the initialization of the array.
app.controller("ProductsController",
[
"$scope", "$q", "productsService", "httpRepository",
function($scope, $q, productsService, httpRepository) {
$scope.productsService = productsService;
$scope.products = [];
$scope.$watch("productsService.products",
function (newVal, oldVal) {
$scope.$apply(function() {
$scope.products = newVal;
});
}, true);
$scope.productsService.getProducts();
}
]);
app.service("productsService",
["httpRepository", "$q", function (httpRepository, $q) {
var products = [];
//populates the products.
const getProducts = function () {
httpRepository.getProducts().then(function (result) {
products = result.data.Products; });
};
return {
getProducts: getProducts,
products: products
};
}
]);
Any help would be appreciated.
Solution 1:[1]
If you are watching the products array of the productsService for changes in values, create a reference to the array itself in your scope:
instead of:
$scope.productsService = productsService;
try:
$scope.productsService = productsService.products;
and:
$scope.$watch("productsService",
function (newVal, oldVal) {...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
