javascript - Angular 代码在第二次单击后起作用

标签 javascript html angularjs

我正在服务器端使用 Java 编写一个网上商店,在客户端使用 Angular 编写。我在使用评论部分后遇到了问题。我的评论列表在我第二次单击发送按钮后刷新,其中包含之前写的评论。因此,要查看我的评论,我需要首先单击将其发送到服务器,然后单击刷新评论数组(但第二次单击后它将发送新评论但不会渲染它)。 请帮忙,我是 Angular 新手

var productApp = angular.module('productApp', []);
productApp.controller('productCtrl', ['$scope', '$location', '$http', function ($scope, $location, $http) {
  var url = $location.absUrl() + '/comments';
  $scope.comments = [];
  function getAllComments() {
    $http.get(url).then(function (response) {
        $scope.comments = response.data;
    });
  }

  var sendComment = function () {
    var comment = {'userName': 'danko', 'content': $scope.comment};
    $http.post(url, comment);

  };
  $scope.send = function () {
    sendComment();
    getAllComments();
  };
  getAllComments();
}]);

模板:

  <ul class="media-list">
                    <li class="media">
                        <div ng-repeat="comment in comments" class="media">
                            <a class="pull-left">
                                <img class="media-object img-circle" src="/resources/img/user.png"
                                     style="width: 64px; height: 64px;">
                            </a>
                            <div class="media-body">
                                <h4 class="media-heading">{{comment.userName}}</h4>
                                     {{comment.content}}
                            </div>
                        </div>
                    </li>
                <br>
                <div class="input-group">
                        <textarea class="form-control custom-control" ng-model="comment" placeholder="Leave feedback" rows="3"
                                  style="resize:none"></textarea>
                    <span class="input-group-addon btn btn-success" ng-click="send()">Send</span>
                </div>
            </ul>

最佳答案

似乎您正在并行运行这两个函数:

$scope.send = function () {
    sendComment();
    getAllComments();
};

根据您的评论,您将在发送(存储)新消息之前收到消息。 您应该做出 promise 来解决此问题:

$scope.send = function () {
    sendComment();
};
var sendComment = function () {
    var comment = {'userName': 'danko', 'content': $scope.comment};
    $http.post(url, comment).then(function(){         
        getAllComments();
    })

};

关于javascript - Angular 代码在第二次单击后起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41212561/

相关文章:

AngularJS 指令输入宽度通过 keyup 调整大小

javascript - 带有 angular-cli 的 ASP.NET WebApi

javascript - json 的 ng-repeat 为另一个 ng-repeat 的值

javascript - Angularjs,如何在 Controller 中单击按钮时重置指令变量?

javascript - 在 UI 上重新定位动态呈现的元素

javascript - Google Chrome 开发人员工具的源代码栏下的这些东西是什么?

javascript - 当存在节点图标时,ASP.Net TreeView 全部展开/折叠不起作用

javascript - 使用jquery获取 anchor 标签的数据值

html - 无法更改页脚背景颜色

javascript - angularjs:最终使用链式 promise