In my controller, I have a function that checks the day and changes the isOpen property of an object based on the time. The object is retrieved using the code snippet below:
$http.get('js/data.json').success(function(data) {
$scope.locations = data;
});
Here's the code snippet:
$scope.checkStatus = function($scope) {
switch(day) {
case 0: $scope.locations[0].isOpen = false;
break;
case 1:
case 2:
case 3:
case 4:
case 5: if( time >= $730am && time < $9pm ) {
$scope.locations[0].isOpen = true;
} else {
$scope.locations[0].isOpen = false;
};
break;
case 6: if( time >= $11am && time < $9pm ) {
$scope.locations[0].isOpen = true;
} else {
$scope.locations[0].isOpen = false;
};
break;
default: alert("default");
};
// More switch statements for other locations...
$scope.checkStatus();
But I encountered an error "Cannot read property 'locations' of undefined." However, when I tested $scope.locations[0].isOpen within the $http.get success function, it worked correctly.
So my questions are: How can I access the object inside the checkStatus function? And is there a better way to achieve this functionality?
Edit:
I managed to resolve the issue by removing the checkStatus() function and directly placing the switch statements inside the $http.get success function. Although it works, I'm not sure if it's the best practice.
myApp.controller('MyController', function MyController($scope, $window, $http) {
$http.get('js/data.json').success(function(data) {
$scope.locations = data;
// variables omitted to save space
switch(day) {
case 0: $scope.locations[0].isOpen = false;
break;
case 1:
case 2:
case 3:
case 4:
case 5: if( time >= $730am && time < $9pm ) {
$scope.locations[0].isOpen = true;
} else {
$scope.locations[0].isOpen = false;
};
break;
case 6: if( time >= $11am && time < $9pm ) {
$scope.locations[0].isOpen = true;
} else {
$scope.locations[0].isOpen = false;
};
break;
default: alert("default");
}
});