简体   繁体   中英

manipulating JSON object in angular

I am using angular and I am using $http.get to get a JSON response back and I set it equal to $scope.myObjects .

When I use ng-repeat="object in myObjects" in the html, it works.

I wanted to know, is there a way to manipulate these objects? I want to create a property called myBoolean and for each object in myObject set myBoolean to true .

When trying to manipulate this object in the controller by doing something like: $scope.myObjects.something I get myObjects is undefined

when I try to view the JSON response in the browser all I see is [object Object]. Is there a tool to view the JSON response?

EDIT: here is my html

<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>

here is my 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;
    });
});

and my service

angular.module('commentService', [])

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

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

That's because $scope.myObjects is an array (ie [] ) , not an object (ie {} ).

So, you would have to loop through the array and access the elements inside them one by one.

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

console.log($scope.myObjects);

$scope.myObjects is actually an array. So to manipulate items present in this scoped variable, you need to iterate it using a loop. For example:

for (index  = 0; index < $scope.myObjects.length; index++) {
  $scope.myObjects[index].myBoolean = yourValue;
}

ng-repeat can repeat a list of items like an array of items/objects of items, but not an Object.

If we do like this:

$scope.myObjects.something = myBoolean; 

it will override the collection so ng-repeat will fail.

Use it like this

Comment.get()
 .success(function(data) {
     $scope.comments = data;
     angular.forEach($scope.comments, function(comment) {
         comment.canEdit = true; // hear we will get each comment so we can set property and value to each commnent
     });
     $scope.loading = false;
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM