I'm trying to wrap my head around Factories and Services in AngularJS and keep getting stuck. Here is a basic example similar to problems i'm trying to solve.
HTML
<div ng-controller="productGridController">
<div ng-repeat="category in categories" ng-controller="productCategoryController">
<input type="text" ng-model="category.name">
<div ng-repeat="product in products">
<input type="text" ng-model="product.name">
</div>
<a class="btn btn-small" ng-click="addProduct()">Add Product</a>
</div>
<a class="btn" ng-click="addCategory()">Add Category</a>
</div>
Now let's say I want to get a total count of all products that are currently instantiated inside of the root controller productGridController
and store it in a variable I can output inside of the productGridController
in a variable such as $scope.totalProducts
Since each productCategoryController
has it's own scope, I'm not sure how to do global counters and sums like that? I think ia service or factory could do something like this but I'm not sure how to implement it.
I tried putting a root scope variable in the productGridController
like this:
app.controller("productGridController", function($scope, $http, $rootScope, $timeout) {
$scope.totalProducts = 0;
$scope.categories = [];
$scope.addCategory = function() {
$scope.categories.push({name:''});
}
});
And then watching whenever something changed in the productCategoryController
app.controller("productCategoryController", function($scope, $http, $rootScope, $timeout) {
$scope.products = [];
$scope.addProduct = function() {
$scope.products.push({name:''});
}
$scope.$watch('products', function() {
$scope.totalProducts = $scope.products.length;
}, true);
});
This works when there's only been one category added, but when there is multiple categories it only factors the most recent one.
Also keep in mind in my real application I'm pulling in the data from a database so this will also need to be able to work in realtime, so the counter function can be called at any point to reflect the current status of how many products there currently is.
What would be the simplest way to do this in Angular JS?