Reputation: 11251
I would like to reflect post request status by showing/hiding success/error html element with the error description. I have following controller with use of $http
service:
$ctrl.addCorporateTransport = function() {
var postStatusBar = angular.element('postStatusBar');
$http.post('/post_corporate_transport', $ctrl.corporateTransport)
.success(function () {
// throw success alert
})
.error(function (error) {
// throw error alert
});
};
I'm looking for having possibility to throw <div class="alert"><p>my error here</p>
if I hit error callback.
I tried this:
var statusBar = angular.element('postStatusBar');
//...
.success(function () {
statusBar.setClass("alert-success")
})
.error(function (error) {
statusBar.setClass("alert-danger");
statusBar.setParameter("text", error);
});
But it doesn't work obviously and looks like anti-pattern. What is the best solution for doing the thing?
Upvotes: 1
Views: 47
Reputation: 232
If the alert component is outside controller scope than you need make the alert a directive and use broadcast to notify and update properties like visibility.
else you can bind properties from controller like:
<div ng-controller="AwesomeController as AwesomeCtrl">
<div class="alert" ng-show="AwesomeCtrl.show.error">....
<div class="alert" ng-show="AwesomeCtrl.show.success">....
<div class="alert" ng-class="{ 'succes' : AwesomeCtrl.show.success }">....
enter code here
angular
.module('app')
.controller('AwesomeController', controller);
controller.$inject = ['$http'];
function controller($http) {
var vm = this;
vm.corporateTransport = {};
vm.show = {
error = false;
success = false;
}
vm.oneCoolMethod = addCorporateTransport;
// test
addCorporateTransport();
function addCorporateTransport() {
$http.post('/post_corporate_transport', vm.corporateTransport)
.success(onTransportSuccess)
.error(onTransportError);
};
function onTransportSuccess(result) {
toggleAlert('success');
}
function onTransportError(result) {
toggleAlert('error');
}
function toggleAlert(level) {
angular.forEach(vm.show, function(value, key) {
vm.show[key] = false;
});
vm.show[level] = true;
}
Upvotes: 2
Reputation: 395
at the first you must using $scope.statusBar and also addClass except setClass
Upvotes: 2