The object $http has not been defined in this context

Recently, I started exploring Angular JS and encountered an issue while attempting to use the $http service in my project. Below is the code snippet that caused the error.

In the code, you can see that I have initialized <ng-app="myapp"> and created a controller for it. Following the tutorial instructions, I registered the controller in View.js and tried to fetch data from a 'data.json' file. However, when running the program, I received an error stating that $http is not defined.

View.html


 <!DOCTYPE html>
<html lang="en">
<head>
<script
    src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<script src="js/View.js"></script>
</head>

<body ng-app="myapp">

    <div ng-controller="Object">
        <span ng-bind="o.rollNo"></span>
        <span ng-bind="o.firstName"></span>
        <span ng-bind="o.middleName"></span>
        <span ng-bind="o.lastName"></span>
        <span ng-bind="o.className"></span>
        <span ng-bind="o.schoolName"></span>
    </div>
</body>
</html>

View.js

var app=angular.module("myapp", []);
app.controller('Object',function($scope,$http) {

    $http.get("data.json")
    .success( function(response) {
        $scope.o= response;
       });

});

data.json:

[
   {
      "rollNo" : "1",
      "firstName" : "ABC",
      "middleName" : "DEF"
      "lastName" : "HIJ"
      "className" : "First"
      "schoolName" : "CRB"
   }
]

Project Structure

Answer №1

Your code is functioning correctly without any issues.

Since you only have 1 object, make sure to access values using index i.e o[0].rollNo

<body ng-app="myapp">

    <div ng-controller="Object">
        <span ng-bind="o[0].rollNo"></span>
        <span ng-bind="o[0].firstName"></span>
        <span ng-bind="o[0].middleName"></span>
        <span ng-bind="o[0].lastName"></span>
        <span ng-bind="o[0].className"></span>
        <span ng-bind="o[0].schoolName"></span>
    </div>
</body>

Controller

var app=angular.module("myapp", []);

app.controller('Object',function($scope,$http) {    
     $http.get('data.Json').
        success(function(data, status, headers, config) {
            alert("Success");
          $scope.o = data;
        }).
        error(function(data, status, headers, config) {
            alert("Error");
          // log error
        });

});

data.Json

Remember to separate key:value pairs with commas

[
   {
      "rollNo" : "1",
      "firstName" : "ABC",
      "middleName" : "DEF",
      "lastName" : "HIJ",
      "className" : "First",
      "schoolName" : "CRB"
   }
]

For your project structure, ensure correct json file path(js/data.json)

$http.get('js/data.Json').
        success(function(data, status, headers, config) {
            alert("Success");
          $scope.o = data;
        }).
        error(function(data, status, headers, config) {
            alert("Error");
          // log error
        });

Answer №2

This crucial information has only been mentioned in a couple of sources:

Consider relocating the following line:

<script src="scripts/ViewController.js"></script>

to the end of the document

    <span ng-bind="data[0].itemName"></span>
    </div>
    <script src="scripts/ViewController.js"></script>
</body>
</html>

... Also, refer to @Name's insight regarding the JSON data file.

Answer №3

Here's a suggested solution:

let app = angular.module("myapp", []);
app.controller('Object', objectCtrl);
objectCtrl.$inject = ['$scope', '$http'];

function objectCtrl($scope, $http){

   $http.get("data.json")
     .success( function(response) {
         $scope.o = response;
   });

}

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

The JSON response is not a standard object

There is a request to retrieve all objects of a Django app, but it is returning a string instead of a plain object as expected. Javascript : $.getJSON("/cadastro/getAllPessoas/", function(data){ console.log(data); console.log(typeof(data)); ...

Is there a way to limit user input on an editable material-table to prevent the entry of characters, special characters, or negative numbers?

I am currently working with an editable material-table, and I would like to restrict the user from entering anything other than numbers in one of the columns. Unfortunately, I couldn't find any information about this in the validation section on the m ...

The 'replace' property is not found in the 'IData' type. What is the missing piece?

I am trying to implement a cast function that can handle strings containing numbers as input. Unfortunately, I am encountering an issue with the "replace()" method when using regex. Does anyone know how I can define the use of "replace()" within the IData ...

Troubleshooting Socket.IO Communication: Client's emits not reaching server

I have implemented a real-time notification service in a web app using Express and Socket.IO. The client can successfully connect to the server and receive emits from it. However, I am facing an issue where the server is not receiving emits from the client ...

Step-by-step guide on adding and removing a row from a table with the help of jquery and node js

I just finished creating a table in jade that includes two select boxes and a single text box. However, I encountered an issue where my row addition functionality stops working after the user makes a selection in the first select box and then changes the ...

Having issues with the delete button when trying to filter data in a list?

Currently, I am working on a list where users can add items with two options: Delete the whole list Delete a specific item. However, it seems that the "handeDelete" button is not functioning properly. Could someone please point out what mistake I made in ...

Manipulating strings in Discord.js

if(msg.content.includes("[mid]")) { let str = msg.content let pokeID = str.substring( str.indexOf("[mid]") + 5, str.lastIndexOf("[/mid") //get the unique-code for a pokemon ); msg.channel.send ...

Using Swift 3 to populate a Tableview with JSON data

Working on developing an app and looking to showcase JSON data in a TableView. Currently, the code successfully saves the JSON-data in an array and can print it in the console. However, the challenge lies in loading this data into the tableview despite try ...

Why is my jQuery blur function failing to execute?

Currently, I am working with HTML and the jQuery library to avoid core JavaScript in order to maintain consistency. In my project, there are 3 fields and when a user clicks on field1 and then somewhere else, I want only field1's border to turn red. T ...

JsonConverting, JObjecting, JPropertying

I have a code snippet here that generates NewtonSoft Jobjects JObject o = new JObject(new JProperty("DataSources", new JArray(from p in repDatasource.DataSources select JObject( JProperty("Columns", new JArray (from q in p.columns select new JObject(new J ...

Forge: Securely encrypting massive files

I rely on the forge framework for implementing PGP functionality, specifically for encrypting large files (2gb or larger) while minimizing RAM usage. What would be the most efficient approach to achieve this? ...

How can I convert string-based data to numerical values within an API response object using JavaScript?

Currently, I am utilizing the Alpha Vantage API through RAPID API. The response object schema from the API appears as shown in the link below: https://i.sstatic.net/FEm0u.png To visualize this data on a chart, I need to remove the quotation marks surroun ...

Distortion of Textures on a Cylinder in ThreeJS

When I try to apply a texture to a cylinder geometry in THREE JS, I encounter some strange distortion issues with the texture. The problem can be clearly seen in this image: https://i.sstatic.net/A80KH.png The cylinder shape is generated using the follow ...

Incorporating an external token within my Angular application

My web server framework is currently hosting a static (Angular) single page application. To authenticate users, they must enter their email address and submit it. Once submitted, users will receive an email with a link in the form of (similar to password ...

Is there a way to extract the data from the JSON file?

In the provided snippet, the terms "results", "geometry", "location", "lat" and "lng" have been hardwired into the code. The issue lies in the fact that if Google decides to modify any of these terms, it could render my code useless. Thus, I am curious if ...

Is there a way to trigger a function after a tooltip or popover is generated using Twitter Bootstrap?

Is there a way to manipulate a tooltip or popover with twitter bootstrap after it has been created? It seems like there isn't a built-in method for this. $('#selector').popover({ placement: 'bottom' }); For instance, what if I ...

Having difficulty retrieving a dropdown value with reactjs

Seeking assistance with retrieving dropdown values in ReactJS. Despite attempting multiple methods, I have been unsuccessful in obtaining the values. Can someone provide guidance on extracting these values? Below is a snippet of my code: <Grid container ...

The brief display of hidden content during Angular route changes is causing visibility issues

Here is an example of a view I have... <section ng-controller="ProfileController"> <div class="alert alert-danger" ng-show="!result.success"> {{result.message}} </div> <div class="container" ng-show="result.success ...

How to Ensure an Element Appears Above Another Despite Z-Index Troubles?

After conducting approximately 2 hours of research on this topic, I was unable to find clear answers or solutions. Hence, I have decided to address the issue here. The problem I'm facing is as follows: Due to the nature of HTML/CSS, it seems impossi ...

Vue appears to be having trouble waiting for the axios Post request

While testing a login request, I encountered an issue where jest did not call the mock: This is my test : const User = '123123' jest.mock('axios', () => ({ get: jest.fn(), post: (_url, _body) => new Promise((resolve, reject ...