In my HTML Page, I have a button
tag that looks like so:
<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
$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:
$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. 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?
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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.