1

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?

1
  • 1
    why dont you go for ng-show by setting some scope variables in responses Commented Dec 14, 2016 at 13:04

2 Answers 2

2

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;
    }
Sign up to request clarification or add additional context in comments.

Comments

2

at the first you must using $scope.statusBar and also addClass except setClass

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.