简体   繁体   English

HTML页面是否在AJAX调用之前加载?

[英]HTML Page loads before AJAX call?

In my HTML Page, I have a button tag that looks like so: 在我的HTML页面中,我有一个button标签,如下所示:

<button ng-hide="alreadyFreinds()" type="button" class="btn btn-primary btn-lg">Friend</button>

However, when I try to access certain parts of the alreadyFriends function shown below, I get an error saying that TypeError: Cannot read property 'length' of undefined 但是,当我尝试访问如下所示的alreadyFriends函数的某些部分时,出现错误,提示TypeError: Cannot read property 'length' of undefined

  $scope.alreadyFreinds = function(){
    for(var i = 0; i < $scope.user.friends.length; i++){
      if($scope.user.friends[i].username === $scope.realUserViewing.username && 
        $scope.user.friends[i].requested == true && $scope.user.friends[i].pending == true){
        return true;
      }
    }
  };

However, the confusing part is that I already have $scope.user.friends and $scope.user defined in a few lines above this function like so: 但是,令人困惑的部分是我已经在此函数上方的几行中定义了$ scope.user.friends和$ scope.user,如下所示:

  $http.get('/api/users/me')
    .then(function(result){
      $scope.user = result.data;
  });

I am a bit confused as to why the HTML page loads and calls tbe alreadyFriends function before the Ajax call completes. 我对为什么HTML页面在Ajax调用完成之前加载并调用tbe yetFriends函数感到困惑。 I tried to use promises to help me solve this and I found 我试图用承诺来帮助我解决这个问题,我发现

AngularJS: How to execute a controller function AFTER completion of AJAX call in a service? AngularJS:如何在服务中完成AJAX调用后执行控制器功能?

But this did not help me too much because when I did 但这对我没有太大帮助,因为当我做了

  $http.get('/api/users/me')
    .then(function(result){
      var deferred = $q.defer();
      $scope.user = result.data;
      deferred.resolve($scope.alreadyFreinds);
      return deferred.promise;
  });

This did work, but the HTML page still loads up before the AJAX call is completed. 确实可以,但是在AJAX调用完成之前HTML页面仍然加载。 Any ideas how to fix this? 任何想法如何解决这一问题? Thanks! 谢谢!

    <button ng-hide="alreadyFreinds()" 
     ng-if="user.length > 0"
     type="button" class="btn btn-primary btn-lg">Friend</button>

By setting ng-if your button will be visible and your alreadyFreinds() will be fired when your http call response get back. 通过设置ng-if您的按钮将可见,并且当您的http呼叫响应返回时,将触发alreadyFreinds()

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

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