Working with AngularJS: Accessing a JSON file from the local directory

The answers to my previous questions on this topic have not been satisfactory.

It seems that most examples and tutorials for AngularJS online always define tiny JSON arrays directly inside the JavaScript code...

So, let's simplify things with a basic example:

(function(){
        var app = angular.module('store', [ ]);
    
        app.controller('StoreController', function(){
            this.product = products;
        }); 
    
        var products = [
            {name: "Linux Mint", origin: "Ireland"},
            {name: "Ubuntu", origin: "Isle of Man"},
            {name: "OpenSUSE", origin: "Germany"},
            {name: "Fedora", origin: "USA"}
        ];
    })();
    

I want to modify the "products" array to load a JSON file from the same folder; I am not allowed to use external tools or frameworks, and I cannot set up servers as suggested in some previous responses. Furthermore, I cannot change the existing code, only the part after the "=", possibly utilizing $scope and $http.

How would you approach this in a functional manner?

Answer №1

Experiment with the following:

(function(){
    var app = angular.module('shop',[]);
    app.controller('ShopController',['$http',function($http){
        this.item=$http.get('data.json').success(function(response){
            return response.data;
        });
    }]);
})();

Answer №2

If you want to try this out, make sure your JSON file is set up in the directory and direct the GET request towards it just like any other GET request. Hopefully, this explanation helps. *This is primarily for mimicking a request, although certain parts may be similar when making a server request.

function CustomController(customService) {
  var vm = this;
  customService.fetchData().then(function(response) {
    vm.data = response;
  });
}

function customService() {
  var Custom = this,
    URLS = {
      FETCH: '/data.json'
    },
    responseData,
    allData;

  Custom.fetchData = function() {
    return $http.get(URLS.FETCH).then(function(response) {
      return response.data
    });
  };
}

Answer №3

If you're looking to read a local JSON file, one approach is using the FileReader. Check out this working example: http://plnkr.co/edit/LtYOyeyxJncnmBGw5YRp?p=preview

app.controller("MainCtrl", ["$scope", function($scope) {
    $scope.jsonString = "";

    $scope.readFromFile = function() {
        if(FileReader) {
            var input = document.getElementById('myFile');
            var file = input.files[0];

            var fr = new FileReader();
            fr.onload = function(e) {
                $scope.jsonString = e.target.result;
                $scope.$apply();
            }

            fr.readAsText(file);
        } else {
            window.alert('FileReader is not found, sorry');
        }
    }
}]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I possess information stored within the array object below, and I aim to transform it into a different array object format

Here is the response I received from my API: let data = [ { date: '2021-04-27', formatted_date: 'Apr 27', location: [ { date: '2021-04-27', formatted_date: 'Apr 27', countr ...

AngularJS function orderBy reverses the array instead of sorting it

I encountered an issue where, after clicking the 'order button', the table does not order as expected. Instead, it reverses all the td elements. For example, 'A', 'C', 'B' becomes 'B', 'C', "A". I ...

Acquire concealed JSON data within an HTML document using R programming

Currently, my goal is to extract data from Transfermarkt primarily using XML + httr package. page.doc <- content(GET("http://www.transfermarkt.es/george-corral/marktwertverlauf/spieler/103889")) Upon retrieval, I noticed a concealed array lab ...

Retrieve every HTML element that is currently visible on the screen as a result

I have a dynamic HTML table that updates frequently, with the potential for over 1000 rows. Instead of replacing the entire table each time it updates, I am exploring options to only update the visible rows. My initial approach involved iterating through ...

Add integer to an array of strings

Currently, I am utilizing an autocomplete feature and aiming to save the IDs of the selected users. My goal is to store these IDs in a string array, ensuring that all values are unique with no duplicates. I have attempted to push and convert the values u ...

Upon clicking the 'Add Image' button, TINYMCE dynamically incorporates an input

I am in search of creative solutions to address an issue I'm facing. Currently, I am utilizing TINYMCE to incorporate text into my webpage. However, I would like to enhance this functionality by having a feature that allows me to add an image along w ...

Adding dots between page numbers when using ReactJS/Javascript Pagination can be achieved by implementing a specific method

I have created a pagination component using React JS. Currently, it only displays all the page numbers, but I want it to show dots when there are more than 8 total pages. Here's how I envision it: c. When total is less than 9 pages: Page 1 selecte ...

Steps to adding a collection of links (stylesheets, javascript files) to each html document

Is it feasible to add a list of links to multiple HTML files? I was inspired by W3 School's W3 Include functionality, which allows you to import blocks of HTML code into various files simultaneously, making it convenient for making changes across many ...

Using a pool.query with async/await in a for-of loop for PostgreSQL

While browsing another online forum thread, I came across a discussion on using async/await with loops. I attempted to implement something similar in my code but am facing difficulties in identifying the error. The array stored in the groups variable is f ...

The response from the XHR object is coming back as "Object Object

Recently, I've been faced with the challenge of working with an API that provides articles. Within the array returned by the API, there are attributes like author, title, and description. However, despite my efforts, each time I attempt to retrieve th ...

Guide on converting HTML datetime picker datetime-local to moment format

I am looking to convert an input type : <input type="datetime-local" name="sdTime" id="stTimeID" onChange={this.stDateTime} /> into a specific date format: const dateFormat = 'MM/DD/YYYY hh:mm:ss a'; To achieve this, I need to transfer ...

Using Typescript/JSX to assign a class instance by reference

Looking to access an object's property by reference? See the code snippet below; class Point{ x:number; y:number; constructor(x,y) { this.x=x; this.y=y; } } const a = { first: new Point(8,9), second: new Point(10,12) }; let someBoo ...

What is the best way to ensure that JavaScript code is executed in a specific sequence?

Even though I understand that Javascript is not the same as C# or PHP, I keep encountering an issue with Javascript - specifically with how I use it. Here's the scenario: function updateStatuses(){ showLoader() //displays 'loader.gif' on ...

Using Pocketbase OAuth in SvelteKit is not currently supported

I've experimented with various strategies, but I still couldn't make it work. Here's the recommendation from Pocketbase (): loginWithGoogle: async ({ locals }: { locals: App.Locals }) => { await locals.pb.collection('users' ...

Tips for updating the value of a $scope variable and running tests with AngularJS Jasmine

For my initial case, the product id should be undefined. var $stateParamsStub = { scheduleId : undefined } Within my controller, I am determining if isUpdate should be true or false. If the productId is undefined, then isUpdate should be false; other ...

Is it possible to create Firebase real-time database triggers in files other than index.js?

Is it possible to split a large index.js file into multiple files in order to better organize the code? Specifically, can Firebase triggers be written in separate JavaScript files? If so, could you please provide guidance on how to do this properly? child. ...

Error: The code is unable to access the '0' property of an undefined variable, but it is functioning properly

I am working with two arrays in my code: bookingHistory: Booking[] = []; currentBookings: any[] = []; Both arrays are populated later in the code. The bookingHistory array consists of instances of Booking, while currentBookings contains arrays of Booking ...

Magical Stylist - Eradicate Indicators while Preserving Labeling

Recently, I've been experimenting with the Google styling wizard in an effort to remove markers while retaining labels for businesses. My objective is to eliminate the marker icons but still display the text labels such as "Jimmy Johns," "Boone Saloon ...

Struggling with rendering an HTML element utilizing jQuery's attribute functionality, encountering issues exclusively in Internet Explorer version

I need assistance with generating and inserting an HTML element using jQuery. In my code, I am including a class attribute for the element as shown below: jQuery('<li></li>', { class: "myClass" }); However, when testing in IE ...

Is it possible to retrieve data from multiple controllers and send it to the server using AngularJs?

I have multiple controllers and I need to retrieve data through these controllers. Ultimately, I want to post this data into the database server. Below is the code snippet which includes the service and controller that I am currently using. However, I am ...