表单提交后,加载微调器(ng-show = loading)始终为true。收到数据后需要将其设为false

时间:2017-07-07 12:02:23

标签: javascript jquery angularjs

我遇到范围变量问题。我通过将ng-show属性设置为true来启动加载微调器,因为很快有人单击我的联系表单上的提交按钮。之后,我将表单数据发送到我的后端,处理后我应该能够将加载spinners ng-show属性设置为false。但是,从后端接收数据后,该属性不会变为false。

这是我的代码。

 $scope.submit = function(){
    $scope.loading = true; //at this point loading spinner appears
    //pass them to api that handles mail sending and
    var contact_name = $('#name').val();
    var contact_email = $('#email').val();
    //var contact_body = $('#contact_body').html();
    console.log(contact_name +" " +contact_email );

    if(contact_name != "" && contact_email != "")
     {

        $.ajaxSetup({
          headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
        });
        $.ajax({
            url: baseUrl+'api/mail',
            type:'POST',
            dataType:'json',
            data: $('#contactFormId').serialize(),
            success:function(data)
            {

                $scope.loading = false;
                console.log("1: Scope loading is set to "+ $scope.loading);             
                if(data)
                {

                        $('.msgHolder').css({
                            'border':'1px solid #9e9c9c',
                            'text-align':'center',
                            'padding':'8px',
                            'color':'green'
                        });

                       $('.msgHolder').html(data.message);
                        $scope.loading = false;
                        console.log("2 Scope loading is set to "+ $scope.loading);  //this is the PROBLEM, conse says $scope.loading is false but the spinner does not go away.

                }
                else
                { 

                //default bg
                        $('.msgHolder').css({
                            'border':'1px solid #9e9c9c',
                            'text-align':'center',
                            'padding':'8px',
                            'color':'red'
                        });
                       $('.msgHolder').html("Email Was not sent. There was an Error.");
                       vcRecaptchaService.reload($scope.widgetId)

                } 
            }
        });
      }
      else
      {
        $scope.loading = false;
        console.log("2: Scope loading is set to "+ $scope.loading); // this actually works. and spinner disappears
         $('.msgHolder').css({
            'border':'1px solid #9e9c9c',
            'text-align':'center',
            'padding':'8px',
            'color':'red'
        });           
        $('.msgHolder').html("Email Was not sent. Required data missing");
      }

    } 

1 个答案:

答案 0 :(得分:4)

您应该使用Angular提供的$http服务。否则,您必须自己告诉Angular数据已更改:

$scope.$apply(function() {
    $scope.loading = false;
});

顺便说一下,你似乎做了许多不是Angular方式的事情(例如触摸DOM)。有原因吗?