Hello, I am currently working on an AngularJS application development project. Within my JSON data, I have information structured like this:
angular.module('app', []).controller('MainController', ['$scope', function($scope) {
$scope.cities = [{
name: "city A",
elements: [{
id: 'c01',
name: 'name1',
price: 15,
qte: 10
}, {
id: 'c02',
name: 'name2',
price: 18,
qte: 11
},
... (truncated for brevity)
}];
$scope.extractSubsities = function(itemSelected) {
if (itemSelected && itemSelected.elements) {
$scope.data = itemSelected.elements;
}
}
});
To improve code cleanliness and adhere to best practices, I want to extract this data into a separate JSON file and call it as follows:
angular.module('app', []).controller('MainController', ['$scope', function($scope) {
$scope.cities = /*insert method to call external JSON here*/;
$scope.extractSubsities = function(itemSelected) {
if (itemSelected && itemSelected.elements) {
$scope.data = itemSelected.elements;
}
}
});
Any help on achieving this would be greatly appreciated.
UPDATE
I attempted the suggestions provided in the responses but encountered issues. Here's what I did:
I set up a XAMPP web server hosting all my files
I modified my script as follows:
angular.module('app', []).controller('MainController', ['$scope', '$http', function($scope, $http) {
$http.get('js/controllers/data.json').then(function(response) {
$scope.cities = response.data;
});
$scope.extractSubsities = function(itemSelected) {
if (itemSelected && itemSelected.elements) {
$scope.data = itemSelected.elements;
}
}
}]);
Here is the content of my data.json file:
{
"data":[{
"name": "city A",
"elements": [{
"id": "c01",
"name": "name1",
"price": "15",
"qte": "10"
},
... (truncated for brevity)
}
Despite these efforts, the data still fails to load. Any further assistance would be welcomed.