Utilize AngularJS to interact with RESTful web services

Here is the JSON data fetched from my web service:

[{"cameraid":"ggh","timestamp":"2016/05/10 01:31","filename":"ffffpg"},
{"cameraid":"mason","timestamp":"2016/05/10 05:31","filename":"aaa.png"}

This is the HTML code I have:

<!doctype html>
<html ng-app="camListApp">
<head>
    <title>Hello AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
    <script>
    var camListApp = angular.module('camListApp');
    camListApp.controller('Hello', ['$scope', '$http', function($scope, $http){
    function Hello($scope, $http) {
        $http.get('http://localhost/camera/list').
            success(function(data) {
                $scope.record= data;
            });
    }
    </script>
</head>
<body>
    <div ng-controller="Hello">
        <table border = 1>
        <thead>
        <tr>
        <th>camid</th>
        <th>Timestamp</th>
        <th>Filename</th>

        </tr>
        </thead>
        <tbody>
        <tr ng-repeat="record in record">
        <td>{{record.cameraid}}</td>
        <td>{{record.timestamp}}</td>
        <td>{{record.filename}}</td>
        </tr>
        </tbody>
        </table>
    </div>
</body>
</html>

https://i.sstatic.net/ppJ7q.png

However, when I view this in my browser, the table remains empty. I am unsure of what I might have missed or done wrong. Can anyone provide any guidance on how to display the data in the table as intended?

Answer №1

Here are some key issues in your code that need to be addressed for it to work correctly:

  1. Ensure you include [] in the module definition. Update it as shown below:

    var camListApp = angular.module('camListApp', []);
    
  2. Fix the controller definition by removing the unnecessary callback function. Only one callback function is needed:

    camListApp.controller('Hello', ['$scope', '$http', function($scope, $http){
      $http.get('http://localhost/camera/list').
        success(function(data) {
            $scope.record= data;
        });
    }]);
    

It is recommended to use .then instead of .success for handling promises.

  1. When using the $http service, remember that it wraps your data in an object and the actual data is accessed through the data attribute in the response. Update your code as follows:

    $http.get('https://api.github.com/users/addi90/repos').then(function(response) {
      $scope.records= response.data;
    });
    

A working sample with data from my github repositories can be found here: https://jsbin.com/qejapayuhi/1/edit?html,js,console,output

Answer №2

To properly set up your HTML, you must designate a name for your app:

<html ng-app="camListApp">

Next, within your script, you will need to define the controller, app, and import necessary services. Wrap the function with:

var camListApp = angular.module('camListApp');
camListApp.controller('Hello', ['$scope', '$http', function($scope, $http){
   // your existing code here
}

Angular has specific requirements for these steps. Since replicating your app is not straightforward, I am curious to know if these instructions resolve your issue.

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

How can I make my webpage unselectable except for specific content within a div using CSS and JavaScript?

During a live editing session, I am looking to make only specific portions of the page selectable. Can someone provide guidance on how to disable selection for everything except within a particular div? ...

How can the button effect be disabled in Vue Material for md-button?

Is there any documentation available for disabling the effect from md-button in Vue Material? Thank you ...

What is the best way to maintain a Tampermonkey script within Selenium?

I'm trying to execute a JavaScript script before the page loads, so I've placed it in Tampermonkey. However, the script doesn't persist after closing the driver. Whenever I run the code again, the saved script is no longer there. This code u ...

Identify Pressed Shift Key Direction - Leveraging JQuery

I am currently working on a web application that requires users to enter capital letters. However, I want to restrict them from using the right shift key for certain keys like a, s, d, f and the left shift key for h, j, k, l in order to detect whether they ...

Using Node.js to generate several MongoDB documents by iterating through JSON data submitted via POST requests

When a webpage sends JSON data via POST to my Node.js App (MEAN-environment using Mongoose), the format of the JSON file is as follows: Firstname: 'XY', Surname: 'asd', Articles: [ { title: '1', description: ...

Creating a curved edge for a shape in React Native can add a stylish and

Issue Description I am working on an app and struggling with styling the bottom navigation bar. It's more complex than what I've done before, especially the curved top edge of the white section and the area between the blue/green circle and the ...

Interactive mobile navigation featuring clickable elements within dropdown menus

I recently implemented a mobile nav menu based on instructions from a YouTube tutorial that I found here. Everything was working perfectly until I encountered an issue on the 'reviews list' page. The dropdown in the mobile nav is supposed to be ...

Assign a CSS class to a DIV depending on the vertical position of the cursor

The website I am currently developing is located at Within the site, there is a collection of project titles. When hovering over a project title, the featured image is displayed directly below it. I would like to change the positioning of these images to ...

Despite Nodejs's efforts, it was unable to successfully populate the user

I have been able to successfully reference and store other documents in my mongodb database as objectids for my application. However, I am facing an issue with the .populate method not working as expected. Below is the code snippet that I am using for po ...

What is the best way to connect my 'Projects' folder to app.js within a React application?

import "bootstrap/dist/css/bootstrap.min.css"; import Navbar from './components/Navbar'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import Home from './components/Home'; import Project ...

Failing to complete a field in the form does not generate an error message when submitted [AngularJS]

My code is designed to display an error message if the user clicks the submit button without filling in a field. However, the functionality is currently not working as intended. <form name="loginForm" ng-submit="loginForm.$valid && login()" n ...

The XHR Get request fails to load the HTML content sent from the Express application

As I embark on building my inaugural express app, I have encountered a shift in sending requests from the front-end. Previously, all requests were initiated by anchor elements for GET requests and form elements for POST requests, with server responses hand ...

Extension for Chrome - Personalized pop-up notification when page loads

I am looking to create a custom alert box that triggers on page load instead of the default one, which I find unattractive and possibly irritating for users. alert('hello'); My current approach involves the following code: manifesto.js "cont ...

Vue Component Update DisorderI hope this meets your expectations

Below is my code using Bootstrap, Vue, and Axios: SETUP: *Please disregard the tab-contents in component_a main.js Vue.component('component_a', { props: ['info'], template: `<div> // Component A template code here } ...

Utilizing express and socket.io for seamless cross-domain communication

Is there a way to activate cross-domain functionality for express.io? I require it for a Cordova application, but when using Chrome, I get an error message saying "No 'Access-Control-Allow-Origin' header is present on the requested resource. Orig ...

How can one access the owner function from a different function?

Check out the example on jsfiddle: https://jsfiddle.net/cg33ov4g/3/ (function($){ var foo='foo_value'; var bar='bar_value'; function getVar(theVar){ console.log(this[foo]); console.log(this[bar]); //the c ...

Secure Angular Rails application complete with authentication features and token authentication

I am currently developing a basic app using AngularJS for the frontend and Rails for the backend. Previously, working solely with Rails made it easy to use the Devise gem and work with Rails views (erb). However, I now find myself in a completely different ...

Increasing the size of text in CSS with the use of ":hover" and then causing it to return to its original smaller size

Allow me to explain my goal here. I have text displayed on my website that I would like to enlarge when the user hovers over it and then shrink back down when they move their cursor away. The issue I'm facing is that after enlarging the text using t ...

Merge objects based on specific property within an array of objects

Is there a way to merge objects based on one property and also add missing Days names in the output? Consider this example: var array = [ { "heure1": "14:00", "heure2": "17:00", "day&q ...

Trouble with the $.inArray function

Encountering an issue with storing objects into an array. However, when attempting to verify the existence of an object using $.inArray, it consistently returns -1. The code is written in AngularJS. <input name="{{question.number}}" ng-clic ...