Using JSON data as a variable within an Angular factory

I'm fairly new to Angular and I am attempting to set the DATA (script.js file) variable in order to retrieve data from a JSON file (books.json). I have read some posts about it but I couldn't grasp how it could be implemented in a factory-style structure.

Thank you in advance! Plunker-Code

Answer №1

$http.get function will provide you with a promise when called. Remember to return this promise from your factory and then handle it in your controller by using then.

Within your factory

app.factory("bookService", ["$rootScope","$http", 
function($rootScope,$http,$q) {
    var getBooks = function(){
      return $http.get('books.json'); // This will give you a promise
    }

  return {
    getBooks: getBooks
  };

}]); 

And within your controller

app.controller("listController", ["$scope", "$location", "$routeParams", "bookService",
  function($scope, $location, $routeParams, bookService) {

    bookService.getBooks().then(function(data){ // Handle the promise using then()
      // Success callback
      $scope.books = data;
    });
  }
]);

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

Learn the process of redirecting to a new page using React JS

Currently facing an issue with the Signup button functionality within the Signin dropdown. Instead of opening a new page, it is displaying below the footer. Seeking assistance on how to redirect to a new page when clicking on the signup button. App.js fi ...

Sharing a Redux action with nested child components

The current structure I am working with looks like this: UserPage -> Container |-----UserList -> Dumb Component |--- User ->Dumb Component My action and dispatch are connected to the container, which is UserPage. function mapStateToProps(state) ...

Having issues with the Angular-UI (bootstrap) popover functionality?

Currently, I am tinkering with implementing a popover on a button using Angular-UI. The tooltips are behaving as expected, however, I am encountering difficulties when trying to incorporate popovers. In my controller, there is minimal code as it only cons ...

Generate a text box that only accepts numbers

I'm in the process of creating a numeric-only input field using VueJS. It's mostly functioning correctly, but there is an issue that needs to be addressed: SUCCESS: Inputting 12 into the text field results in both the VueJS value and visual dis ...

CSS Class Returns to Inactive State

One of my tasks involves adding a new class to an image. .bbbLink img { outline: 1px solid #ddd; border-top: 1px solid #fff; padding: 10px; background: #f0f0f0; } When hovering over the image, I apply the following styles, .bbbLink img ...

Retrieve a PHP file utilizing Javascript or JQuery

Is there a more straightforward method than using ajax to retrieve the contents of an HTML or PHP file and place it within a div on the current page? I am familiar with the process through ajax, but I am curious if there is a simpler alternative that doe ...

Convert JavaScript to TypeScript by combining prototype-based objects with class-based objects

My current challenge involves integrating JavaScript prototype with class-based programming. Here is an example of what I've tried: function Cat(name) { this.name = name; } Cat.prototype.purr = function(){ console.log(`${this.name} purr`) ...

Is there a way for me to intercept JavaScript code before it runs on Chrome?

Looking to develop a Chrome extension for the developer tools that can intercept JavaScript code on a current web page prior to compilation or execution by the browser. I aim to instrument the JS code before it runs in the browser. Could someone assist wi ...

Executing HTML code from an AJAX response is a common task when working with web

I am integrating the MyPos payment gateway for debit card purchases. However, I have encountered a strange issue with their SDK. When initiating the payment process, the SDK attempts to output HTML code with a form that will auto-submit to their checkout p ...

Saving the JavaScript console to a MySQL database: A step-by-step guide

I have purchased a JavaScript code online for running a spinwheel game. Now, I am looking to save the results from the spinwheel into a MySQL database. The JavaScript code already provides a result function, but I'm unsure how to save the result data ...

Using jQuery to vertically center a div

When a vertical menu on my website is clicked, it pops out from the left side of the screen. The content inside is vertically centered using CSS transformations. While expanding to show sub-items, everything remains centered. However, there's an issue ...

The sortBy function yields an object rather than an array

Code snippet below is in question: $list = Elements::where('list_id', $id)->with('visitors')->get()->sortBy(function($t) { return $t->visitors->count(); }); return json_encode($list); The current code returns an obje ...

Identifying the End of Rendering in Three.js

Is there a way to accurately determine when rendering has been completed? I attempted the following method: scene.add( mesh ); render(); mesh.onBeforeRender = function(renderer, scene){ ... } mesh.onAfterRender = function(renderer, scene){ ... } Ho ...

Issue with Bootstrap 4 Navbar collapsing and not expanding again

Help needed! My navigation bar collapses when the window is resized, but clicking on the hamburger icon does not open it back up. I have included my code below. Can someone please provide guidance on how to expand the collapsed navbar? <html lang=&quo ...

using an array as an argument in the filtering function

Is there a way to pass an array to the filter method in JavaScript? I have successfully filtered an array using another array. However, my filter array currently has a global scope. How can I pass the array to make my code cleaner? var array = [1, 2, 3, ...

Rails-powered web application for voice over IP services

My initial project idea involved implementing VoIP functionality between a mobile app client and web browser using Rails as the back-end. However, after conducting some research, I found myself with a number of questions. Firstly, in my search, I noticed ...

Utilizing the JSON result of an AWS MySQL query to display data as a DataTable on a webpage

I recently managed to link a website to a Lambda function via AWS API Gateway to execute a SQL query on an Aurora Serverless MySQL database. The JSON response is currently displayed in string form on the webpage, appearing like this: https://i.sstatic.net ...

Utilizing ThemeProvider in a Different Component in React

In my App.js file, I have a function that toggles between light and dark mode themes: import { createTheme, ThemeProvider } from '@mui/material/styles' import Button from '@mui/material/Button' import Header from './components/Head ...

Ways to maintain scroll position unaffected by postback?

In my JavaScript code, I have an event set to trigger at regular time intervals that clicks on a specific ASP button. This event is part of a chat room application where the gridview inside a panel needs to be refreshed frequently to display new chats. H ...

"When trying to access a jQuery ID, it is coming back as undefined even though the

I'm attempting to obtain the ID of a specific element, save it as a variable, and then utilize that ID value to interact with other elements in the same section bearing the identical ID. <div class="mainContent"> <div class="articleContent"& ...