4

I'm very new to Angularjs and am having issues figuring out how to update a $scope element I created from JSON. Basically I have a service that contains the function which grabs the JSON:

app.service('JSONService', function($http){         
    return{
        getJSON: function(){
            return $http.get('posts.json')
                .then(function(response){
                    return response.data;
                });
        }
    };
 });

I then have a Controller that contains a function that gets the JSON data on button click and puts it in $scope.data and a second function that I would like to use to update $scope.data:

app.controller('PostController', function PostController($scope, JSONService){
    $scope.data;

    $scope.getJSON = function(){            
        $scope.data = JSONService.getJSON();
    };
    $scope.addPost = function(){
        // Add to $scope.data
    };
});

Currently, I successfully grab the JSON data and am able to use it to populate aspects of my view, but I am stuck on how to proceed with updating $scope.data so that:

  1. It actually updates
  2. The update is reflected in my view

I have tried $broadcast, $scope.data.push, $scope.data.posts.push. These have either flat out not worked or given errors. I'm sure it might be a simple answer, but I feel I may be inexperienced with Angularjs and JSON to pick up on it. Thanks in advance.

2 Answers 2

3

So I think there are a couple issues with the code above. Hopefully this can help you get it straightened out:

The $http.get() function returns a "promise". Promises have a then() function, which you are using, but you should probably adjust to take the data that gets returned and put it straight into $scope. Doing a "return" statement inside the then() in your service does not really have anywhere to go at that point since the request was async. Angular knows how to work with promises, so you can bind to the data in the UI, but you will actually not find the data directly under $scope.data. $scope.data will still be a promise object, and the data will be in another property (something like $scope.data.promiseData -- don't remember exactly what the property is though). You could adjust like this:

app.service('JSONService', function($http){         
    return {
        getJSON: function() {
            return $http.get('posts.json');
        }
    };
})

Controller:

app.controller('PostController', function PostController($scope, JSONService){
    $scope.data;

    $scope.getJSON = function(){            
        JSONService.getJSON()
            .then(function (response) {
                $scope.data = response.data;
            });
    };
    $scope.addPost = function(postText){
        // Add to $scope.data (assuming it's an array of objects)
        $scope.data.push({postText: postText});
    };
});

HTML:

<div data-ng-repeat="post in data">{{post.postText}}</div>

<input type="text" ng-model="newPostText">
<button type="button" ng-click="addPost(newPostText)">Add Post</button>
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome thanks! I had to use $scope.data.posts.push({key: value, ...}); but that's just because of my JSON data. So I was basically never actually assigning the data to $scope.data?
Correct. $scope.data never really had the data. It was a promise object (see Angular docs for $q service, which $http uses internally). Your UI worked because of some Angular magic in working with promises, but you would not have found your actual data in $scope.data.
0

Actually, whilst the above code is correct, in this case, the getJSON function isn't actually called anywhere, so the $scope.data is never populated.

1 Comment

IN addition, any changes pushed only push to the local scope and are never appended the JSON file, so each time the page is refreshed, you will loose all changes. If you want persistence you would require, localStorage (e.g. ngStorage) or a database

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.