Is it possible to alter the JSON file being loaded in AngularJS by passing a variable?

I am in need of loading the content from either food1.json or food2.json, and I am attempting to achieve this within the html template:

  <body ng-controller="MainCtrl" ng-init="init('food1')">

Subsequently, in the JavaScript code:

$scope.init = function (name) {
    $scope.name = name;
    $scope.category = name + ".json";
    $scope.foodlist = {};
    $http({
        method: 'GET',
        url: $scope.category,
    }).success(function (data, status, headers, config) {
        {
            $scope.foodlist = data;
        }
    }).error(function (data, status, headers, config) {
        // something went wrong :(
    });
};
});

The category name is correctly concatenated: By printing I am {{ category }}, I receive "I am food1". However, no food items are being displayed. It appears that there might be an issue with my JSON call.

You can find my Plunkr here

Answer №1

It appears that you forgot to include $http in your controller. Make sure to update your code to:

app.controller('MainCtrl', function($scope, $http) {

instead of:

app.controller('MainCtrl', function($scope) {

SEE DEMO

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

Terminal throws an error stating that no default engine was specified and no extension was provided

I have been working on executing a backend program in Node.js using MongoDB. I have created a form with two input fields for password and name. I am not utilizing any HBS or EJS and my VS Code terminal is displaying the following error: No default engine ...

Struggling with Windows Azure Mobile Services and data serialization issues

I'm facing a challenge trying to integrate my model type with Windows Azure Mobile Services. It's functioning well, except for when I introduce the following member: [DataMemberJsonConverter(ConverterType = typeof(DictionaryJsonConverter))] ...

Unable to eliminate top margin in Bootstrap 3 affix feature

Struggling to locate the source of the margin-top when utilizing the affix plugin on my Navbar. You can view [my website here] for better understanding. Should I be implementing Javascript to solve this issue? My current skills in that area are not very ...

Using web3Provider in a Next.js environment

While attempting to integrate Web3-react v6 into my Next JS project, I encountered an error when trying to wrap my entire app with the provider. In _app.jsx, I included the following code: import React from 'react'; import { Web3ReactProvider } ...

What could be the reason for the malfunction of Twitter Bootstrap's typeahead feature in this case?

Struggling to implement typeahead.js into my current project. Despite having bootstrap loaded, the source code does not mention anything about typeahead. As a result, I included the standalone js file with hopes of making it work. Upon implementation, the ...

Statement after post is not yielding any result

Below is a javascript function that I'm struggling with: function loginsubmit() { var url = "../php/loginsubmit.php"; var data = ""; ajaxRequest(url, "POST",data , true, insertNewBody); } This function is responsible for sending an ajax ...

Is there a method to run code in the parent class right after the child constructor is called in two ES6 Parent-Child classes?

For instance: class Parent { constructor() {} } class Child { constructor() { super(); someChildCode(); } } I need to run some additional code after the execution of someChildCode(). Although I could insert it directly there, the requirement is not to ...

Submitting the Ajax form will result in the quantity of the product in the cart being updated while remaining on

Hello, I am using ajax to keep the user on the same page after submitting a form. If successful, I will use ajax load to load another page that displays the quantity of the product. However, I am facing an issue where each subsequent submit increases the q ...

What is the reason for not encountering an error when reading an array beyond its index limit?

Recently, while working on a pre-existing website with JavaScript code, I made an interesting discovery. I noticed that the code was accessing array items in a unique way: var value = myArray[0, 1]; This seems to be retrieving the second item of the arr ...

Retrieve JSON data using AJAX one by one

I am facing a minor issue with my code. Let's consider a JSON structure like the one below: [{"img":"john.png","name":"John","username":"@john"}, {"img":"mark.png","name":"Mark","username":"@mark"}] My desired data organization is: John @john john. ...

Tips for passing a URL variable into an Ajax script to prefill a form input in a search field

I have a website with a search feature that dynamically queries a database as you type in the search field, similar to Google's search suggestions. This functionality is achieved through AJAX. As the results appear on the page while you enter your se ...

Is it possible to retrieve resolved parameters from a template-rendering function?

I'm facing a scenario where I have a state setup like this .state('dropdown', { url: '/dropdown', views: { "@":{ template: ...

Guide to running code repeatedly in node.js

Is there a way to repeat the console.log function 5 times in Node.js using the 'repeating' npm package? I am working on a node application that needs to run a specific code multiple times, but I can't seem to figure out how to achieve this. ...

Angular does not wait for the backend service call response in tap

Does anyone have a solution for subscribing to responses when the tap operator is used in a service? edit(status) { dataObj.val = status; // call post service with status.. this.service .update(dataObj) .pipe(takeUntil(this._n ...

Prevent the use of unnecessary object properties

Currently, my project involves using Typescript and React in conjunction with Material-UI. Specifically, I am utilizing Material-UI's styling solution, which implements CSS in JS methodology in a Hook-like manner as outlined in their documentation: co ...

Having trouble installing handlebars on Node using the command line

I've been attempting to integrate handlebars with node using the instructions from my book. The guide advised me to install handlebars like so: npm install --save express3-handlebar. However, this resulted in an error npm WARN deprecated express3-han ...

The parent component is failing to pass the form values to the child form group in CVA

My Angular application (view source code on Stackblitz) is running Angular 15, and it utilizes reactive forms along with a ControlValueAccessor pattern to construct a parent form containing child form groups. However, I am encountering an issue where the d ...

Encoding a field as a JSON object

I'm trying to send a JSON body to a REST service, but the service is quite old and requires a POJO with a JSON string field. The structure of the POJO looks like this: class SomeData { int id; SomePojo jsonField; ... } Therefore, the So ...

Encountered an error message stating "This dependency was not found" after installing a package using npm

I recently added a package called htmldiff to my Vue project using the npm install command. The next step was to try importing the package into one of my components. import { diff } from 'htmldiff'; // note that the package does not use default ...

formik does not support using the "new Date" function as an initial value

I have been trying to set the initial value of a date in my component like this, but when it renders I am encountering an error. const formik = useFormik ({ initialValues: { dob: new Date () } }) During this process, I'm facing the follow ...