A guide on how to add JSON data to an array using AngularJS

Is there a way to dynamically populate the label in the treedata_avm array with data from $scope.moduleSelected instead of using hardcoded values?

app.controller('treeController',['$http','$scope','dataService',function( $http,$scope,dataService){

    $http.get('WS/tree').success(function(data,status){
        $scope.modules=data;
        $scope.moduleSelected = $scope.modules[0].MODULE_NAME;
        $scope.moduleSelectedId = $scope.modules[0].ID;
        $scope.moduleSelectedParentId = $scope.modules[0].PARENT_ID;

     console.log($scope.modules);
     console.log($scope.moduleSelected);
     console.log($scope.moduleSelectedId);
     console.log($scope.moduleSelectedParentId);


    }).error(function(data){
        $scope.modules=data || "Request failed";
        console.log("Request failed "+ $scope.modules);
    });

    }]);

treedata_avm:

treedata_avm = [
  {
    label: 'Animal',
    children: [
      {
        label: 'Dog',

      }, {
        label: 'Cat',

      }, {
        label: 'Hippopotamus',

      }, {
        label: 'Chicken',
        children: ['White Leghorn', 'Rhode Island Red', 'Jersey Giant']
      }
    ]
  }]

Answer №1

To trigger an action when the user changes the input field, you can use the event listener 'onchange' on the specific field linked to $scope.moduleSelected. However, it is unclear why such functionality would be necessary in this context.

Answer №2

$http returns data using its success promise resolve function in the format: response.data

In this case, it is recommended to first set:

$http.get('WS/tree').success(function(response){
    $scope.modules = response.data;
    $scope.treedata_avm = response.data
}).error(function (){...})

If you plan to use treedata_avm in a view, make sure it is assigned to $scope.treedata_avm. Otherwise, it can be used as a variable within the controller.

It's advisable to move the logic involving $http into a provider (factory, service, provider) and then call it from there. Keep controllers lightweight and place the main logic in providers for reusability.

I hope this information proves helpful.

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

Upon refreshing the browser page, AngularJS fails to redirect to the default page as expected

In my AngularJS route configuration, I have set up the following paths: moduleA.config(function($routeProvider){ $routeProvider. when('/A',{templateUrl:'A.jsp'}). when('/B',{templateUrl:'B.jsp'}). wh ...

How does Backbone.js tackle error handling when receiving messages from Rails?

Can anyone using backbone.js lend a hand? How can error messages from a rails app be encoded when integrating with backbone.js? For instance, how should flash messages like "record not found" be handled? While errors are usually defined on the client sid ...

Leveraging jq for extracting and displaying key value pairs enclosed in quotation marks

I need help extracting specific key/value pairs from a file. The content of the file is shown below: { "Job": { "Name": "sample_job", "Description": "", "Role": "a ...

Obtain a JSON array within an ArrayList

I am having trouble retrieving all my data from the database due to a compilation error, and I am new to android development. In my class, I am trying to fetch all users from a table and display their names in a listview. If there is no name available, the ...

Sample information in Plain Old Java Object for JSON reference

I am in the process of documenting my JSON API. My API returns Java POJOs that are serialized by Jackson. I am developing a service to provide example JSON for each endpoint. What I want to achieve is similar to the following: class MyPojo { @Example(" ...

Issue encountered with JSONWriter.setDateFormatter following the update of Struts framework from version 2.3.7 to 2.3.33: NoSuchMethodError

After upgrading from Struts version 2.3.7 to 2.3.33 using Maven, my web application which previously worked without any issues now encounters an exception when attempting to access a web page with an Ajax call to the server. The error message received is ...

How can I choose a JToken using JSONPath when there are multiple possible name options to consider?

I have a JSON object structured like this: { category1: { items [ ... ] } } It could also be represented as: { category2: { items [ ... ] } } My goal is to extract the JArray of items using a single JSONPath. Is there a ...

Separating the login/register functionality from the main app using the MEAN Stack

Apologies for my poor English! I have developed an application using the MEAN stack (MongoDB + Express.js + Angular.js + Node.js) with authentication utilizing passport.js and JWT (jsonwebtoken and express-jwt). What I aim to achieve? The login and r ...

Calculate the sum of the elements within an array that possess a distinct attribute

I need to calculate the sum of certain elements in an array. For example, let's consider this array: var sampleArray = [ {"id": 1, "value": 50, "active": true}, {"id": 2, "value": 70, "active": false}, ...

Interfacing Highcharts with Angular for seamless data binding across series

I am fairly new to using highcharts and I am having difficulty binding my data into the series parameter. In my controller, I have an array of objects that I want to display (when I use console.log, I can see that they are all properly there) this.plotDa ...

Moving specified data from one interactive table to another interactive table

In my setup, there are two tables - one for products and another for customers: <table cellpadding="0" cellspacing="0"> <thead> <tr> <th>Product Code</th> </tr> </thead> ...

Creating dynamic HTML table rows with data from a JSON object

Query: In search of a Jquery or JavaScript solution for generating dynamic table rows with colspan using the JSON structure provided below. I am encountering difficulties in creating the necessary rows and have attempted several approaches without success ...

Identify if the initial value of a BehaviorSubject in RxJS has been altered

Is there an easy method to determine if I am working with the original value of a BehaviorSubject or if it has been altered using "next"? ...

Verifying whether the user is requesting their own page using ASP.NET MVC and AngularJS

My current project involves using asp.net mvc alongside angularjs. How can I include additional data (such as an isOwner variable) along with the user object being returned? var isOwner = false; if(user.Alias == User.Identity.Name) isOwner = true;) In my ...

ngTable select all data that has been filtered

I have encountered an issue with selecting only the rows from an ng-table that have been filtered. The current code filters the table rows successfully, but it also selects rows that are not displayed: Controller: let sampleData = [{id: 1, name: 'Jo ...

Unable to upload a JSON file to MongoDB

While using RockMongo in Openshift to import a json file into a MongoDB database, I came across an issue. The json was exported directly from another MongoDB without any modifications. Here is a snippet of the json data: { "_id" : "10352", "author" : "89 ...

What is the reason for needing to use utf8_decode prior to inserting a UTF8 string into MySQL?

I encountered a perplexing issue that I was able to resolve by experimenting with different options. However, the solution doesn't quite make sense to me... Here's the scenario: I am receiving JSON data from Facebook encoded in UTF-8. My databas ...

An introduction to the basics of AngularJS, AJAX, and ASP.NET MVC

I am struggling with creating a simple AngularJS example that makes an AJAX call to an ASP.NET MVC action method. I have tried various approaches but haven't been successful yet. Below is the code snippet I have been working on... The ASP.NET MVC act ...

API does not support the grant type

I'm attempting to retrieve a token from the server response. It works perfectly fine using Postman, but when I try to debug it on Android, I encounter an error: unsupported_grant_type Below is my code snippet: HttpClient client = new DefaultHttpC ...

Is there a term in JavaScript that denotes an object that can be serialized into JSON format?

Can you help me find a term for basic objects that accentuates their simplicity? Particularly, objects that do not reference themselves and do not have any methods or bindings (i.e. JSON-serializable). The terms I am currently using are: "flat object" " ...