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

Modifying various states within React using the useState() hook

Curiosity strikes me - what actually happens when I modify more than one state in a handler function? Will they be updated simultaneously, or will the changes occur sequentially? const [x, setX] = useState(0) const [y, setY] = useState(0) const handlerFu ...

Retrieving data attributes from model within a Backbone view using Underscore template

I have a Backbone.js view that I'm working with: var StreamV = Backbone.View.extend({ tagName: 'div', className: 'stream', events: { }, initialize: function () { this.listenTo(this.model, 'change' ...

Encountering a problem with Selenium when dealing with tabular data displayed in a DIV format on a website, where each row is encapsulated within its own DIV element

While creating Selenium automation tests for a website with multiple rows contained within a main DIV element, each row represented by a separate DIV. For example, if there are 5 dynamically generated rows, the HTML code structure would look like this: < ...

`Can you explain how to specify the elements of an array within a form using AngularJS?`

Below is an array containing objects: //Data source code $scope.data = [ { name: 'Lname', items: [{ label: 'Lastname', type: 'text', model: 'lname', pattern: '/^[a-zA-Z]$/', ...

Contrasting Template Helper and Template Variable in Meteor.js

What sets apart the use of a Template Helper from a Template Variable (if that's not the right term)? How do you determine when to utilize each one? In the following example, both Template.apple.price function and the quantity function in Template.ap ...

Trying to access the 'style' property of a null value is causing an error

Although I have come across several questions related to this particular error, unfortunately, none of them provided a solution. Below is the HTML code: <!DOCTYPE html> <html> <head> <title>ChatRoom</title> <link ...

Automatically scroll the chat box to the bottom

I came across a solution on Stackoverflow, but unfortunately, I am having trouble getting it to work properly. ... <div class="panel-body"> <ul id="mtchat" class="chat"> </ul> </div> ... The issue lies in the JavaScript t ...

Leverage OpenID Connect in Azure Active Directory with authentication code flow

Currently, I am developing an authentication system for a NodeJS and Express web application that requires users to be directed to Microsoft SSO. To achieve this, I am utilizing passport-azure-ad and OpenID Connect. My main query is - Is it mandatory to ...

Toggling javascript functionality based on media queries

On one of my slides, I want to display images that are specific to different devices like iPhone, iPad, and desktop. I am looking for a way to filter these images based on the device. Using display:none won't work as it's JavaScript, but here is ...

Unable to connect List to dropdown in angular

Having trouble connecting dropdown with a List in AngularJS: <select> <option ng-repeat="x in list">{{x}}</option> </select> app.controller('myCtrl', function($scope) { $Scope.list=[{id:1, name='name 1' ...

Using jQuery to load a text file and dynamically insert it into a specified div

How can I load a *.txt file and insert the content into a div? Here is my code: JavaScript: $(document).ready(function() { $("#load").click(function() { $.ajax({ url : "file.txt", success : function (data) { ...

Sharing data between pages in Ionic and Angular with POST requests

Currently, I am utilizing Ionic for developing a mobile application and have decided to incorporate very basic authentication (without any security measures) into the app. The process involves validating user credentials against a database through a POST r ...

methods for retrieving nested JSON data from an API endpoint

My data has been exported in JSON format { "count":79, "stories":{ "23658975":{ "title":"NOMINATIVO", "description":"BUSDRAGHI PIERGIORGIO", "updated_at":"2013-06-16T18:55:56+02:00", "created_at":"2013-06-16T18:39:06+02:00", "du ...

js.executeScript produces a Unexpected identifier error

Visit this link for proofs Running a script in the browser console on the specified page: let img = document.querySelector('.subscribe'), style = img.currentStyle || window.getComputedStyle(img, false), bi = style.backgroundImage.slice(4, -1).re ...

What is preventing me from assigning a value of false to my JavaScript variable?

I'm encountering an issue where the articleExists variable is not being set to true on line 6, even though I have used console logs to double check that the if statement containing it is functioning properly. app.post("/articles", function(req, res) ...

Reducing file size through compression (gzip) on express js version 4.4.1

My express js app is functioning as a web server, but I am having trouble with serving unzipped static content (js and css files). I have tried using compression from https://github.com/expressjs/compression, but it doesn't seem to be working for me. ...

What is the process for incorporating attribute values when constructing XML with fast-xml-parser?

Latest fast-xml-parser update: version 4.3.6 Description I'm trying to incorporate an xml attribute (tokenized="true") in this format : <custom-tag tokenized="true">test test &gt; 14</custom-tag> Input Code var def ...

Ways to incorporate a conditional statement within a dropdown menu

When a user interacts with a dropdown, I want to conditionally show different choices based on their selection. If the user clicks on a checkbox, a specific set of options will appear; if they click on a radio button, another set of options will appear. h ...

Unable to utilize the resolved value received from a promise and returned from it

Within the code snippet below, I am retrieving a Table object from mysql/xdevapi. The getSchema() and getTable() methods return objects instead of promises. The purpose of this function is to return a fulfilled Table object that can be used synchronously i ...

Click event dynamically bound to list items

I have a web application built with Durandal and Knockout. Here is the HTML code snippet: <ul id="header"> </ul> In a JavaScript function, I am dynamically adding a list item as follows: $("#header).append('<li id="btn"><a hre ...