Angular modifies the structure of a JSON string

Currently, I am attempting to display data on my screen utilizing AngularJS, ASP.NET, and JSON.NET. I have noticed that when I make a call to $.getJSON, it returns a standard JSONArray. However, when I assign this data to a variable inside my Angular controller, the data undergoes some changes and Angular fails to display it properly on my view.

Data Model

public class Directory
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Note> Notes { get; set; }
    public int ParentId { get; set; }
    public List<int> DirectoryIds { get; set; }

    public virtual Directory Parent { get; set; }
    public virtual ICollection<Directory> Directories { get; set; }
}

.NET Controller Action

public string GetDirectories()
{
    var directories = db.Directories.Where(d => d.ParentId.Equals(0)).ToList();

    return JsonConvert.SerializeObject(new { directorylist = directories }, Formatting.Indented,
                    new JsonSerializerSettings
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    });
}

Angular JS

(function () {
    var app = angular.module('notes', []);

    app.controller('DirectoryController', function () {
        this.directories = directories; //Review output 1
    });

    var directories = $.getJSON("/Directory/GetDirectories", function (data) {
        return data; //Review output 2
    });
})();

Output 1 (view a larger image at )

Output 2

Answer №1

Upon reading Claies' comment and receiving a helpful response from Protector, it became clear that the getJSON call was asynchronous, causing issues with loading the var directories before the page fully loaded.

The solution involved using $http.get within the controller and creating a variable to store the context, which was achieved by initializing var cont = this. To prevent errors upon page load, the directories variable needed to be initialized with an empty array.

Subsequently, the data from the success Promise was assigned to the directories variable to ensure proper functionality.

(function () {
    var app = angular.module('notes', []);

    app.controller('DirectoryController', ['$http', function ($http) {
        var cont = this; //Preserve the context
        cont.directories = []; //Initialize with an empty array to prevent errors on page load

        $http.get('/Directory/GetDirectories').
          success(function (data, status, headers, config) {
              //Assign async data to directories within the correct context
              cont.directories = data;
          }).
          error(function (data, status, headers, config) {
          });
    }]);
})();

Grateful for the assistance. The feedback from @Claies and the response from @Protector aided in finding a suitable solution independently.

If there are alternative solutions, feel free to share them for consideration as the preferred answer.

Answer №2

When using the jQuery method getJSON, data is retrieved asynchronously and not returned directly. One approach is to configure your controller within the success function parameter:

var folders = $.getJSON("/Folder/GetFolders", null, function (data) {
    app.controller('FolderController', function () {
        this.folders = data;
    });
});

It's important to remember that the first parameter of getJSON is a data object sent to the server; whereas in the example provided, a JavaScript function is used.

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

Guide to activating MySQL query in Express

After creating a Nodejs Express app with a button on the client side, I want to execute a SQL query on the server side when the button is clicked. Is there a method to achieve this? The code in index.ejs: <button onclick='add()'>+1</but ...

Is there a more efficient method for performing multiple JavaScript replace calls rather than executing them individually?

In my Javascript code, I am creating a string that includes HTML content. Currently, my approach involves the following steps: var filter = ""; filter = util.getTemplate( "tmp_filter", temps ); filter = filter.replace( 'id="tmp_filter"','& ...

Custom AngularJS Directives for Enhancing Chrome App and Android 'Webview' Elements

I'm currently in the process of transitioning an existing Chrome packaged app to incorporate Angular. So far, everything seems to be working smoothly. However, I am facing a challenge when it comes to updating the UI from outside Angular, specifically ...

Struggling to implement sparklines for real-time data in the AngularJS adaptation of the SmartAdmin template

Currently, I am embarking on a project that involves utilizing the AngularJS version of the SmartAdmin Bootstrap template foundhere. Within this project scope, I am required to integrate sparklines into various pages. I have successfully implemented them ...

Ability to access functions from required modules that are defined within the calling module

Is there a way to call a function within a required module that is defined in the main program without copying or creating separate files? Main.js: var http = require('http'); var aFunc = function() {return 1;} var bFunc = require('./bFunc ...

Utilizing Cell References in the Table Component of React Material UI

I'm exploring React and aiming to create an editable table that dynamically updates the $/Unit cell based on changes in the Price and Units cells. I'm having trouble figuring out how to access values from other cells. Can this be achieved using ...

What is the recommended sequence for using decorators in NestJS: @Body(), @Params(), @Req(), @Res()?

How can I properly access the res object to send httpOnly cookies and validate the body with DTO? I keep running into issues every time I attempt it. What is the correct order for these parameters? ...

What is the best way to create a new object in a Vue component with optimal efficiency?

Currently, I am working on initializing a map that would be utilized in my calculatePrice function. calculatePrice(key) { let prices = new Map({ 0: 17, 1: 19, 2: 24, 3: 27, 4: 30, 5: 46, 6: 50 ...

How can I utilize a CDN for JavaScript libraries in Gulp?

As a newcomer to AngularJS and Gulp, I recently encountered an example where certain libraries are copied by Gulp from the 'node_modules' folder into a 'js/lib/angular2' directory: gulp.task('libs', function() { return gulp. ...

Storing user input in MongoDB after encoding

I am currently exploring the most effective methods for storing and presenting user input in MongoDB. In traditional SQL databases, it is necessary to encode all user input as a precaution against injection attacks. However, in the context of MongoDB, ther ...

Transmit JSON from PHP to an autocomplete feature and include a data attribute in the input field

[{ "id": "39", "name": "John Doe", "code": "060400000" }] $(document).on("input", ".autocomplete", function(event) { var name = $(this).prop('id').split('_').pop(); $(".autocomplete").autocomplete({ source: function(request, respo ...

Encountering an "undefined" error when implementing the useReducer hook in React

I'm encountering an error when using the UseReducer hook in React. Even though I have destructured the state object, I still receive this error: const [{previousOperand,currentOperand,operation},dispatch] = useReducer(reducer,{}); return ( ...

Any ideas on how to resolve this ajaxToolkit issue?

Just for your reference, here's what I'm trying to achieve: https://i.stack.imgur.com/GYaNz.jpg Error 1: Unknown server tag 'ajaxToolkit:CalendarExtender'. <ajaxToolkit:CalendarExtender FirstDayOfWeek="Monday" PopupPosition="Botto ...

Compatibility of Typescript with local storage

Can Typescript interact with local storage in any way? I have been setting items using the following code: localStorage.setItem('someString', JSON.stringify(MyTypescriptObject)); This method stores the object as a plain string. For example: ...

"Dynamically generated websites, backend processing, React framework Nextjs, Content Management System WordPress

I'm interested in creating a primarily static site using Next.js, but I also need the ability to provide customers with price estimates based on their specifications. The calculation process needs to be kept private and not exposed to anyone else (oth ...

The functionality to scroll to the top of the page is not functioning properly in Next.js when navigating to a new page using the Link

While using Next.js, I encountered an issue where opening a new page would maintain the scroll position from the previous page. For instance, if I had scrolled to the bottom of a product listing page and clicked on a specific product, the product details p ...

Show a component when there is no input value, then conceal it when an input value is present

Recently, I attempted to position a paragraph absolutely in relation to an input element. My goal is to conceal the paragraph when the input has a value, and reveal it when the input is empty. Here is the code snippet I created, however, it doesn't ...

Using a Vue.js component in a Laravel Blade template can be achieved by first registering the component

I added a component registration in my app.js as shown below: Vue.component('navbar', require('./components/Navbar.vue')); Now I am looking to import that component into my blade.php file like so: <template> <nav class="navb ...

Transitioning from left to right, picture smoothly scrolls into view using Way

I've explored various websites and even attempted to decipher a waypoint guide, but unfortunately, I haven't had any success. The scroll function doesn't seem to be working with the code below. (source: ) Any assistance on this matter would ...

Tips for returning the slider to its default position when a tab is deselected

A fantastic code snippet can be found at this link for creating an animated navigation bar. The only thing left on my wishlist is for the slider to reset to its original position if a tab is not selected. Currently, it remains static regardless of selectio ...