简体   繁体   English

推入阵列后的角度清除对象

[英]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. 但是,由于数据绑定而我清除$scope.post时,该帖子为空。 So my question is how can i avoid this? 所以我的问题是如何避免这种情况?

You can make a copy using angular.copy() which will return a new object with no references to the original. 您可以使用angular.copy()进行复制,这将返回一个没有原始对象引用的新对象。

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 如前所述,应等待成功清除实时版本

It's because of asynchronous nature of Ajax call - your $scope.post = {}; 这是由于Ajax调用的异步特性-您的$scope.post = {}; is executed earlier than success / error callbacks. 在成功/错误回调之前执行。 You should do clearing $scope.post inside the callback, not outside. 您应该在回调而不是外部清除$scope.post

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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