playing with JSON data in angular

Currently, I am utilizing AngularJS and making use of $http.get to fetch a JSON response which I then assign to $scope.myObjects.

After implementing ng-repeat="object in myObjects" in the HTML, everything seems to be functioning properly.

My query pertains to manipulating these objects. Is there a method through which I can create a new property named myBoolean and set it to true for each object within myObject?

Upon attempting to manipulate this object in the controller by executing something like: $scope.myObjects.something, I encounter an error stating myObjects is undefined

When I attempt to view the JSON response in the browser, all that is visible is [object Object]. Is there a tool available for viewing the JSON response?

EDIT: Here is the HTML snippet:

<div class="comment" ng-hide="loading" ng-repeat="comment in comments">
    <h3>Comment <% comment.id %> <small>by <% comment.author %></h3>
    <p><% comment.text %></p>
    <div class="col-sm-6">
        <p><a href="#" ng-click="deleteComment(comment.id)" class="text-muted">Delete</a></p>
    </div>
</div>

Below is the controller:

angular.module('mainCtrl', [])


.controller('mainController', function($scope, $http, Comment) {

$scope.commentData = {};


$scope.loading = true;


Comment.get()
    .success(function(data) {
        $scope.comments = data;
        $scope.loading = false;
    });
});

Lastly, here is the service code:

angular.module('commentService', [])

.factory('Comment', function($http) {

return {
    // get all the comments
    get : function() {
        return $http.get('/api/comments');
    },
});

Answer №1

One important distinction is that the variable $scope.myObjects contains an array - denoted by [], rather than an object - represented with {}.

As a result, in order to manipulate the data within $scope.myObjects, you will need to iterate through each element of the array individually.

angular.forEach($scope.myObjects, function(myObject){
    myObject.isSelected = true;
});

console.log($scope.myObjects);

Answer №2

When working with $scope.myObjects, keep in mind that it is an array. To make changes to the elements within this scoped variable, you'll have to loop through it. Here's a simple example of how this can be done:

for (i = 0; i < $scope.myObjects.length; i++) {
  $scope.myObjects[i].myVariable = updatedValue;
}

Answer №3

ng-repeat is capable of repeating a list of items such as an array of items or objects, but not an entire Object.

If we attempt to do the following:

$scope.myObjects.something = myBoolean; 

it will overwrite the collection causing ng-repeat to fail.

To prevent this issue, use the code snippet below:

Comment.get()
 .success(function(data) {
     $scope.comments = data;
     angular.forEach($scope.comments, function(comment) {
         comment.canEdit = true; // Here we can iterate through each comment and assign properties and values
     });
     $scope.loading = false;
 });

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

I am puzzled as to why my code in React is rendering twice without any apparent reason

I ran into a strange issue where my console.log("hi") was being displayed twice. I was working on a simple todo-list project and noticed that everything was getting double clicked. After some troubleshooting, it seems like the code is executing any JavaScr ...

Calculate the total of all values associated with a dynamically generated key within an array of objects

I'm trying to calculate the sum of similar keys in an array of objects. Each object in the array will have some common keys, but not all arrays will share the same set of keys. I'm considering storing these keys in a separate array and then loopi ...

The occurrence of an unanticipated character '#' was found

I'm currently facing an issue while using webpack to load dependencies. Whenever I execute the npm run dev command, I encounter the following error: Uncaught Error: Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: ...

Getting started with React Native project

Just dipping my toes into the world of React Native and looking for recommendations on the best starter kit/generator to kickstart my projects. Tried out "create-react-native-app" already, but curious if there are any other generators or kits out there tha ...

Obtain the URL value using jQuery and place it inside a <span> element

How can I insert a href value into the span tag like this? <p class="name"> <a download="adja-lo.pdf" title="adja-lo.pdf" href="http://localhost/MatrixDRSnews/apps/Matrix/server/php/files/adja-lo.pdf">adja-lo.pdf</a> </p> ...

Origin of SVG Circle Stroke

Describing my current issue is proving to be challenging, but I'll do my best: My project involves creating an SVG circle progress bar and fortunately, I came across a great example that aligns with what I aim to achieve. I prefer not to use any thir ...

Error encountered in NEXT JS: Unable to parse URL from /api/projects or Error message: Failed to connect to 127.0.0.1:3000

Currently utilizing: export const getStaticProps = async () => { export const getStaticPaths = async () => { and accessing my API (pages/api/projects/) created with Next.js on my local host const res = await fetch("http://localhost:3000/api/ ...

Incorrect Tooltip DisplayWhat could be causing the issue with

I am facing an issue when trying to add a tooltip to a glyphicon within a tile. It doesn't seem to work correctly when it should. However, placing the tooltip outside of the tile works fine. I'm quite perplexed and would greatly appreciate any as ...

Using Kotlin to work with JSON strings that contain line breaks and variables

In need of help adding linebreakers to a JSON string for improved readability. val myString = "some string" val myObjectJson = ` { "example1": "value", "example2": $myString }` This will allow me to utilize ...

ES6 promises: the art of connecting functions with parameters

Looking for a way to chain functions with delays? Here is an example of what I have tried: Promise.resolve() .then(setKeyframe('keyframe-0')) .then(delay(3000)) .then(setKeyframe('keyframe-1')) .then(delay(3000)) .then(setKeyframe(&apo ...

Chrome displaying an extJs Button image

Could it be that Chrome is evolving into the new IE in terms of CSS issues? Here is the code I have for creating ExtJS buttons within an accordion: var button = Ext.create('Ext.Button', { text: '<img src="'+resp.sellers.externa ...

Challenge with JavaScript personalized library

No matter how many times I review my code, I find myself perplexed. Despite my efforts to create a custom library of functions from scratch (shoutout to stackoverflow for guiding me on that), the results are leaving me puzzled. A javascript file is suppose ...

A guide on accessing JSON files from a Cosmos DB container using Python scripts

I need to retrieve a JSON file from the container, make changes to it, and save it back in JSON format. I have read-only access to Cosmos DB. Here is an image of Cosmos DB: https://i.stack.imgur.com/SWSdz.jpg I encountered the following error: CosmosRes ...

Prevent unchecking a checked list item by clicking on it

Is it possible to prevent the user from unchecking a list item once it has been checked? Your assistance is greatly appreciated! $(".collectioncontainer ul li").click(function(){ $('.collectioncontainer ul li.checked').not(this).removeClass( ...

VueJS and Vite: Encountering an unexpected character '�' while attempting to import files that are not JavaScript. Keep in mind that plugins are required for importing such files

I'm puzzled by the error message I'm receiving: [commonjs--resolver] Unexpected character '�' (Note that you need plugins to import files that are not JavaScript) file: /..../..../WebProjects/..../ProjectName/node_modules/fsevents/fse ...

Using anchor tags to send HTML code through email

I currently have an anchor tag on my website that looks like this: <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e0d11131b11101b3e0d11131b09161b0c1b501d1113">[email protected]</a>?subject=Wel ...

The NewtonSoft JSON SerializeObject function does not properly escape fraction values within strings

Encountering a problem where my object is being serialized using Newton with one of the properties containing fraction values like 1/2", 1/4", and so on. Once serialized, I pass the variable to a SQL Server Stored Procedure that utilizes OPENJSON. The is ...

Should you opt for returning [something] or (nothing) in Javascript with ExpressJS?

Is there a distinct contrast between returning something and returning nothing? Let's take a look at an example: user.save(function(err){ if ( err && err.code !== 11000 ) { console.log(err); console.log(err.code); res.send(&apo ...

WARNING: Firebase Alert - User callback encountered an exception. Issue: Unable to update headers once they have been sent

We are currently in the process of developing a new application that utilizes Firebase as our database and express as the middleware/backend for routing our RESTful APIs, which are then utilized by our front-end built with Reactjs. Take a look at our serv ...

Converting Java byte[] arrays into ArrayList using Gson

Using Gson for object serialization and deserialization can be tricky, as Gson tends to convert byte[] arrays into ArrayLists. Here is an example of an Object class: public class RequesterArgument implements Serializable { private Object data; pu ...