Marc Rasmussen
Marc Rasmussen

Reputation: 20555

angular clearing object after pushing to array

So i have the following object:

 $scope.post = {user_id: $sessionStorage.user.user.id};

with this i have the following:

<textarea class="form-control" ng-model="post.text" style="overflow:scroll;height:150px;max-height:150px"></textarea>

On submit i want to do the following action:

    $scope.addPost = function () {
    $http.post(api.getUrl('post', null),
        {
            post: $scope.post
        }).success(function (response) {
            $scope.post.id = response;
            $scope.posts.push($scope.post);
        });

    $scope.post = {};
}

However when i clear $scope.post because of the databinding the post is empty. So my question is how can i avoid this?

Upvotes: 0

Views: 670

Answers (2)

charlietfl
charlietfl

Reputation: 171689

You can make a copy using angular.copy() which will return a new object with no references to the original.

This also removes any hashkeys that angular scope has added to the object which can be problematic when server sees unrecognized keys

$scope.addPost = function () {
 var postData = angular.copy($scope.post);
    $http.post(api.getUrl('post', null),
    {
        post: postData
    }).success(function (response) {
        $scope.post.id = response;
        $scope.posts.push(postData);
        $scope.post = {}; //wait for success to clear
    });    
}

As already noted should wait for success to clear the live version

Upvotes: 2

shershen
shershen

Reputation: 9993

It's because of asynchronous nature of Ajax call - your $scope.post = {}; is executed earlier than success / error callbacks. You should do clearing $scope.post inside the callback, not outside.

Upvotes: 1

Related Questions