Why doesn't my ng-hide on a failed json request?
<div ng-controller="MainController">
<div ng-hide="onError">
Name: {{ user.name}}
Location: {{ user.location}}
Image: <img ng-src="{{user.avatar_url}}" />
</div>
</div>
var MainController = function ($scope, $http) {
var onUserComplete = function (response) {
$scope.user = response.data;
}
var onError = function (reason) {
$scope.error = "Could not fetch the user";
return true;
}
$http.get("https://api.github.com/users/robconery")
.then(onUserComplete, onError);
}
I would change your div
to instead hide when $scope.error
is populated like so:
<div ng-hide="error">
Your onError
function can remain as it is, but you don't need to return true. It can just populate $scope.error
and your div will hide because $scope.error
is truthy:
var onError = function (reason) {
$scope.error = "Could not fetch the user";
}
The onError
method needs to be on the scope. Right now you have it declared as a var
on the controller.
Instead, try:
$scope.onError = function(reason) {
$scope.error = "Could not fetch the user";
return true;
};
In the HTML it should also be written as: ng-hide="onError()"
Note, however, that onError
always returns true
, so it would always hide the div. You should base the ng-hide
on the $scope.error
variable the way David Spence mentioned. If it's populated it would be truthy and hide the div, otherwise you will need to reset it when there is no error. So most likely in your onUserComplete
function you would assign $scope.error = null;
Another option is to use the controller as
approach, which would still require the way you define the function to be defined. Check out the documentation for examples.