What is the best method to extract and manipulate data from a JSON file in an AngularJS application?

personManagerInstance.getString("firstname",'common','en') I am currently passing a direct string in the UI which is affecting it. What I actually need is to read the data from a JSON file and return it as a string.

personManagerInstance.getString("firstname",'common','en') method needs to read the data from a JSON file and return it as a string or object?

personManagerInstance.getString("lastname",'registration','en') This method reads the JSON from a different location based on parameters and returns it as a string.

var PersonManager = function ()
{
  return {
    $get: function ($http, person)
    {
       var mainInfo = $http({
                              method: "get",
                              //"js/resources-locale_en_es.json"
                              url: "js/resources-locale_en_es.json"
                          }).success(function (data) {
                               return data.title;
                          });
      return {
        getPersonFirstName: function ()
        {
          return "as";
        },
        getPersonLastName: function ()
        {
          return person.lastname;
        },
        getString: function (labelid, moduleName, language)
        {
          //Here am getting the value id, moduleName, language based on the vaule I need to change the url path
          //(i.e) js/resources-locale_en_es.json, js/registration/resources-locale_en_es.json
          
          var l = maininfo.success(function (data) {
                               person.firstName = data.title;
                          })
          return person.firstname;
        }
      };
    }
  };
};

angular.module("mainModule", [])
  .value("person", {
    firstname: "",
    lastname: ""
  })
  .provider("personManager", PersonManager)
  .controller("mainController", function ($scope, person, personManager)
  {
    person.firstname = "John";
    person.lastname = "Doe";
    $scope.personInstance = person;
    $scope.personManagerInstance = personManager;

  });
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>

  <script src="script.js"></script>
</head>

<body ng-app="mainModule">
  <div ng-controller="mainController">
    <strong>First name:</strong> {{personManagerInstance.getPersonFirstName()}}<br />
    <strong>Last name:</strong> {{personManagerInstance.getPersonLastName()}}<br />
    <strong>Full name:</strong> {{personManagerInstance.getString("firstname",'common','en')}}  {{personManagerInstance.getString("lastname",'registration','en')}}<br />
    <br />
    <label>Set the first name: <input type="text" ng-model="personInstance.firstname"/></label><br />
    <label>Set the last name: <input type="text" ng-model="personInstance.lastname"/></label>
  </div>
</body>
</html>

Answer №1

There are no issues with utilizing $http.get('data.json'), afterwards, you can utilize angular.toJson(response) to convert JSON string into an object.

http://plnkr.co/edit/6JTuzH8Fb6CNPt3mDqY2

Answer №2

Here is the answer to your query:

$http({
    method: "get",
    url: "insert link to your JSON data here"
}).success(function (response) {
     callback(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

Ways to specify the styles for tr, td, and label elements within a material table

Hey there! Currently, I'm working with material table in react. I came across this page: https://material-table.com/#/docs/features/styling, where it mentions that we can use cellStyle, headerStyle. But what if I want to add more detailed styles to e ...

Adjusting iframe height based on its source URL using JQuery

Currently, I have implemented a script to adjust the height of YouTube iframes in order to maintain a 16:9 aspect ratio while keeping the width at 100% of the container. The challenge I am facing is ensuring that the script only affects YouTube videos and ...

React: executing function before fetch completes

Whenever I trigger the ShowUserPanel() function, it also calls the getUsers function to retrieve the necessary data for populating the table in the var rows. However, when the ShowUserPanel function is initially called, the table appears empty without an ...

What is the best way to push a variable after employing the split function in JavaScript?

error: An unexpected TypeError occurred while trying to read property 'push'. The error was on this line: " this.name[i].push(arrayData[0]); " I'm confused because the console.log statement before that line shows "data is loaded:" alo ...

Expanding Headers with JavaScript

Looking to add a Stretchy Header Functionality similar to the one shown in this GIF: Currently, on iPhones WebView, my approach involves calling a Scope Function On Scroll (especially focusing on Rubberband Scrolling) and adjusting the Image Height with C ...

Development of a chart application involving frontend and backend components, utilizing chartjs for data visualization, mongodb for storage

As a beginner in generating charts using the ajax mechanism and chartjs, I've encountered an issue where the graphs are being plotted incorrectly. Any guidance on how to improve would be greatly appreciated. Thank you! Here is my JavaScript code for ...

Creating unique appbars for different sections on my sidebar in ReactJs

I am trying to implement a responsive drawer and AppBar using material-ui (@material-ui/core). My goal is to display a specific AppBar for each section of the drawer. For instance, when the user navigates to the Timetable section, I want the AppBar label t ...

Building routes for a stationary website with Angular

Currently, I am in the process of developing a static site using a combination of HTML, CSS, and JS along with nodeJS and express for server-side functionality... One challenge I am facing is setting up routes to display pages like /about instead of acces ...

including a close button when in use and excluding it when not in use

Seeking assistance with removing the "close" icon if it is not active. Here is the code I currently have $("#mason2 li div").click(function() { $(this).parent().hide().appendTo("#mason2").fadeIn(200); $(this).append('<p class="close"& ...

A method for arranging an array of nested objects based on the objects' names

Recently, I received a complex object from an API: let curr = { "base_currency_code": "EUR", "base_currency_name": "Euro", "amount": "10.0000", "updated_date": "2024 ...

Creating a mandatory 'Select' dropdown field in Vue.js

Hello, I am a beginner in VueJS and I am trying to make a select element from a drop-down list required. I attempted to add the required attribute as shown in the code below. Any suggestions on how to achieve this? Thanks. <v-select ...

Preventing direct URL access with Angular redirects after refreshing the page

My website allows users to manage a list of users, with editing capabilities that redirect them to the /edit-user page where form information is preloaded. However, when users refresh the page with F5, the form reloads without the preloaded information. I ...

A guide to implementing the map function on Objects in Stencil

Passing data to a stencil component in index.html <app-root data="{<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d4d7d6f5d2d8d4dcd99bd6dad8">[email protected]</a>, <a href="/cdn-cgi/l/email-pro ...

Executing a PHP script after successful execution of another script

tag, I am encountering the following script: Two minor issues: With the button being disabled after a click, it wont allow to click again if for instance an error is returned as shown above. It should only disable it after the input has been released $fo ...

Successive promises of catches

Here is a situation that I am dealing with: controller.ts methodA(): void { myServive.someMethod() .then( () => console.log("then") ) .catch( e => { console.log("catch"); }); } service.ts someMethod(): ng: ...

Using various conditions and operators to display or conceal HTML elements in React applications, particularly in NextJS

I am seeking ways to implement conditional logic in my React/Next.js web app to display different HTML elements. While I have managed to make it work with individual variable conditions, I am encountering difficulties when trying to show the same HTML if m ...

Can you explain the process of accessing data from [[PromiseValue]] while utilizing React hooks?

My current challenge involves fetching data from an API and utilizing it in various components through the Context API. The issue arises when I receive a response, but it's wrapped under a Promise.[[PromiseValue]]. How can I properly fetch this data ...

Content Security Policy Error triggered by Iframe Source Running Script in Web Extension

My web extension for Firefox utilizes a content script to add HTML to a webpage when a button is clicked. The injected HTML includes an iFrame nested in multiple div elements. Below is the relevant part of the content script: var iFrame = document.create ...

AngularJS login form with JSON data

I am currently learning Angular and focusing on the login form implementation. The specific model I am working with can be found in this PLNKR. There are two challenges that I am struggling to resolve. Issue 1: I'm trying to figure out how to tur ...

Invoke the designated JavaScript function within a subordinate <frame>

Below is an example of the standard HTML structure for a parent page named "index.html": <html> <head> <title>test title</title> </head> <frameset cols="150,*"> <frame name="left" src="testleft.html"> ...