As a junior developer, I may be overlooking something obvious, but I'm really struggling with my Angular webapp. I'm trying to load a hash-dictionary that maps environment names to arrays of hosts, like
{development: ["dev.8090", "host.dev.9009"]}
, and then use this dictionary to determine the current host. My plan is to pass the location.host variable to a method called getEnv, which should return the corresponding environment key.
The dictionary loads successfully, but when I attempt to access it inside the getEnv method, it mysteriously becomes an empty object. It's not undefined, just empty. Here's a snippet of my code:
var app = angular.module('app', ['ngResource', 'ui.bootstrap', 'ui.router']);
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
function AppController($scope, $http) {
window.MY_SCOPE = $scope;
$scope.env = "Local";
$scope.dict = {};
$scope.loadDict = function() {
$http.get('api/call/').
success(function(data){
for (env in data.environment) {
var key = data.environment[env].name;
$scope.dict[key] = data.environment[env].hosts;
}
console.log($scope.envDict)
}).error(function(data){
console.error(data);
})
};
$scope.getEnv = function(host) {
for (key in $scope.dict) {
for (value in $scope.dict[key]) {
if ($scope.dict[key][value] === host) {
$scope.env = key;
}
}
}
};
$scope.loadDict();
$scope.getEnv("host1");
}
Oddly enough, I can manually trigger these methods and receive the expected output in the console by using the MY_SCOPE variable. If I hard-code the dictionary, everything works fine. Interestingly, if I log $scope.dict from anywhere else in the code except within the $scope.getEnv function, it displays correctly. But as soon as $scope.getEnv is executed, $scope.dict turns into an empty object.
I've experimented with hard-coding keys into the dictionary, rearranging the code structure, and even attempting to move the loadDict method into a factory - all without success. Any suggestions or ideas on how to solve this issue?