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

时间:2014-09-05 08:01:38

标签: javascript html ajax angularjs

在我的HTML页面中,我有一个button标记,如下所示:

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

但是,当我尝试访问下面显示的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;
      }
    }
  };

然而,令人困惑的部分是我已经在这个函数上面的几行中定义了$ scope.user.friends和$ scope.user,如下所示:

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

我有点困惑的是为什么HTML页面在Ajax调用完成之前加载并调用了alreadyFriends函数。我试图用promises来帮我解决这个问题,然后我找到了

AngularJS: How to execute a controller function AFTER completion of AJAX call in a service?

但这对我没有多大帮助,因为当我做的时候

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

这确实有效,但HTML页面仍然在AJAX调用完成之前加载。任何想法如何解决这一问题?谢谢!

1 个答案:

答案 0 :(得分:0)

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

通过设置ng-if,您的按钮将会显示,当您的http呼叫响应返回时,您的alreadyFreinds()将被触发。