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

Testing AngularJS controllers that implement moment.js functionality

I am in the process of creating unit tests for a controller that utilizes moment.js to manage three dates within a week. The testing framework I am using is jasmine and my AngularJS version is v1.3.15 In essence, there is an init() function that initializ ...

Angular functions are executed twice upon being invoked within the html file

I decided to kick-start an Angular project, and I began by creating a simple component. However, I encountered a perplexing issue. Every time I call a function in the HTML file from the TypeScript file, it runs twice. TS: import { Component, OnInit } from ...

Creating an input field within a basic jQuery dialog box is not possible

Can anyone assist me in adding an input box to my dialog box? I am working with jquery-ui.js. Here is the code I currently have: $(document).on("click",".savebtn",function(). { var id = $(this).attr("id"); $.dialog({ ...

Guide to importing simulated data from a JSON file in Angular 2 Karma Jasmine tests

Currently, I am working on creating karma jasmine test case for angular 2. We have encountered a requirement to mock data in a separate JSON file due to the large amount of data (to maintain code cleanliness). After extensive research, we were unable to f ...

If IE's conditional comments are dysfunctional

Could this be a silly question? I feel puzzled by it. I've been using an if IE conditional statement to address some issues in IE6. In the head section, this is what I have: <!--[if lt IE 7] > <script type="text/javascript" src="js/ie6.js" ...

Tips on how child component can detect when the object passed from parent component has been updated in Angular

In the child component, I am receiving an object from the parent component that looks like this: { attribute: 'aaaa', attribute2: [ { value }, { value }, { value }, ] } This object is passed to th ...

steps for transferring a shallow copy of an array to a function

How can I adjust this code so that when I press each button, the console.log displays a different slice of the array instead of always showing me the last 20 elements? for (var i = 0; i < array.length; i++) { var b; var NewArr = []; ...

What could be causing my node.js to fail in producing a true result within the return statement?

I've encountered an issue with VS code where the return true command is not displaying anything in my terminal, while console.log(map[arr2[j]]) successfully returns true. I'm unsure if this problem lies with node or my terminal. How can I ensure ...

What specific data am I sending from my ajax request to the MVC controller?

How can I determine the appropriate parameter to use when passing a JavaScript object? Please see below: var all = []; //iterate through each instrument for (var i = 0; i < 3; i++) { var txt = getThis(i);//int var detail =getThat(i);//string ...

An elusive melody that plays only when I execute the play command

I am currently working on creating a music Discord bot using the yt-search library, however, I am encountering an issue where it returns undefined when trying to play a song and joins the voice channel without actually playing anything. My approach is to u ...

Make sure to always display the status bar and soft keys

Is there a way to set up my ionic app on Android so that the status bar is always displayed at the top and the soft keys are shown at the bottom? I attempted to add this line to the config.xml file, but it didn't work. <preference name="Fullscree ...

Managing form submissions using Jquery and checkboxes

Whenever I submit my dynamically created form, all checkboxes briefly become selected for a split second. Does anyone have an explanation for this behavior? Is it common or is there something wrong with my code? Although the form submits correctly, it migh ...

What could be causing bundle.js to remain in a pending status on my website?

Whenever I try to open a page from my project, the browser keeps showing loading forever and in the network tab, the status of bundle.js is pending. (Interestingly, if I open other routes of the project, everything works fine). If I remove all product var ...

The Dynamic Duo: AngularJS and Thymeleaf

Has anyone tried combining Thymeleaf and AngularJS before? Which framework should take priority in rendering content? Suppose you have a Thymeleaf select element and would like AngularJS to populate it with a list of commands from a data source... < ...

Are you experiencing issues with the cross-origin request failing in react-map-gl?

While setting up a map in react-map-gl and providing my access token, I encountered the following console error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://events.mapbox.com/events/v2?access_token= ...

Having trouble fetching the correct URL from JSON using PHP

Here is what I'm aiming to achieve: [{ "id": "1", "url": { "small": "http://website/images/image.jpg", "large": "http://website/images/image.jpg" }, }] This is the code I have written: <?php defined('DS') ...

Error: Attempted the use of 'append' method on an object lacking the implementation of FormData interface, with both processData and contentType set to false

Apologies for any English errors. I am attempting to use ajax to submit a form, and here is my JavaScript code: $("#formPublicidad").on('submit', function(event) { event.preventDefault(); var dataForm = new FormData(document.getElementBy ...

Is it possible to hide a menu by removing a class when the user clicks outside the menu?

I've come across a lot of information about how to close a menu when clicking outside of it, but my question is, can the following code be simplified to something like if you don't click on #menu > ul > li > a then removeClass open. Can ...

The value attribute in the HTML input tag being dynamically increased by JavaScript

Hi there, can someone help me figure out how to save changes to the value attribute of an HTML input tag that is being incremented by JavaScript? Currently, every time I click on a specific element, the input field should increase by one. The problem is th ...

There was an error in locating the JavaScript file within the Node.js Express Handlebars application

My website is not displaying the .js file, css file, or image from the public folder. Here are the errors showing up in the console: GET http://localhost:8080/assets/images/burger.jpg 404 (Not Found) GET http://localhost:8080/burgers.js net::ERR_ABORTED ...