Reputation: 14429
I'm currently performing an ajax call and if an error is returned, I'd like to apply an error class to an element. What's the best/optimal/easiest way to perform this?
Upvotes: 0
Views: 84
Reputation: 19193
If the element and the Ajax call are part of the same controller/directive, simply update your scope. For instance
ajax().error(function(e) {
$scope.error = true;
});
And in the HTML, the element will get the class "something-is-wrong"
<div ng-class="{'something-is-wrong': error}"> ... </div>
Now if you also want to display the error message, intead of a boolean you could put the messahe inside scope.error
ajax().error(function(e) {
// Or just $scope.error = "Cannot do stuff"
$scope.error = formatMessage(e);
});
html:
<div ng-class="{'something-is-wrong': error}"> {{error}} </div>
Finally, if the ajax call is not in the same environment than your element, you could rely on a service.
module.factory('errorService', function() {
return { error: null };
});
ajax().error(function(e) {
errorService.error = e;
});
Html (after adding errorService to your scope):
<div ng-class="{'something-is-wrong': errorService.error}"> ... </div>
Upvotes: 2