Hello everyone, I'm facing some challenges with AngularJS. I've spent the entire day trying to solve this issue but as a beginner, I'm really stuck and hoping for some assistance. The error I'm encountering is 'Cannot read property 'length' of undefined'. In my program, I have an array of objects called '$scope.products' sourced from a .json file. I am filtering this array to display only products under the category 'special offers'.
$scope.specialOffers = $filter('filter')($scope.products,{category:"Special
Offers"}, true);
After filtering, I want to determine the length of this new array and use it in my randomInt function to generate a random integer between 0 and the length of the array. However, the '$scope.specialOffers' variable is showing up as undefined for some reason. Here is my complete controller code:
app.controller('ProductsController', ['$scope','$filter', 'productFactory',
'$location', '$routeParams',
function ($scope, $filter, productFactory, $location, $routeParams) {
$scope.path;
$scope.category;
$scope.products;
$scope.rand;
$scope.specialOffers;
$scope.id = $routeParams.id;
specifyCategory();
getProducts();
$scope.specialOffers = $filter('filter')($scope.products,{category:"Special Offers"}, true);
$scope.rand = randomInt($scope.specialOffers.length, 0);
function specifyCategory() {
$scope.path = $location.path();
if ($scope.path == "/products/woodentoys") {
$scope.category = "Wooden Toys"
} else if ($scope.path == "/products/woodenaccessories") {
$scope.category = "Wooden Accessories"
} else if ($scope.path == "/products/specialoffers"){
$scope.category = "Special Offers"
}
}
function getProducts() {
productFactory.getProducts()
.then(function (response) {
$scope.products = response.data;
}, function (error) {
$scope.status = 'unable to load product data ' + error.message;
});
}
function randomInt(max,min){
max++;
return Math.floor((Math.random())*(max-min))+min;
}
}]);
This is my first time asking a question on Stack Overflow, so your patience is greatly appreciated. Thank you in advance!