Munded
Munded

Reputation: 97

Displaying error messages in index.html thrown by controller

I am trying to implement a voucher system via pushing relevant buttons and I want it to display unique error messages on the page if user is not eligible for the discount.

    <tr name="vouchers">
  <td>
    <button type="button" class="btn" id="five-pound-voucher" ng-click="ctrl.addFiveVoucher()">£5 off voucher
    </button>
    <button type="button" class="btn" id="ten-pound-voucher" ng-click="ctrl.addTenVoucher()">£10 off voucher
    </button>
    <button type="button" class="btn" id="fifteen-pound-voucher" ng-click="ctrl.addFifteenVoucher()">£15 off voucher
    </button>
  </td>
  <td></td>
  <td>DISPLAY ERROR MESSAGE HERE</td>
  <td></td>
  <td></td>

My discount methods look similar to this:

self.addFifteenVoucher = function() {
    if(self.subTotalPrice >= 75  && self.containingShoes) {
        self.fifteenPoundVoucher = true;
        self.setTotal();
    }
    else {
        throw new Error("Not Eligible for £15 discount")
    }
}

Is there way to display this error message with angular without using flash messages or jquery. ng-message does not seem to be the right thing to use. Any help would be greatly appreciated!

Upvotes: 1

Views: 871

Answers (3)

Corey Michael Cochran
Corey Michael Cochran

Reputation: 33

inside where you have

<td>DISPLAY ERROR MESSAGE HERE</td>

you could set up a bootstrap styled error message and bind it to a message set from your controller as seen below.

<div class="alert alert-danger" role="alert" ng-if="errorMessage">
  <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
  <span class="sr-only" data-ng-bind="errorMessage"></span>
</div>

you could set this errorMessage property you are binding to in the else block where you were previously throwing an error. would look something like below

instead of

else {
    throw new Error("Not Eligible for £15 discount")
}

do

else {
    //possibly $scope.errorMessage depending on how you use your controller
    self.errorMessage = "Not Eligible for £15 discount"; 
}

Upvotes: 1

ecif
ecif

Reputation: 311

I'd push errors into an array on the controller side and display it like this:

<div class="alert alert-danger" ng-show="validationErrors.length">
  <ul>
    <li ng-repeat="error in validationErrors">
    {{error}}
    </li>
  </ul>
</div>

Upvotes: 2

Michael
Michael

Reputation: 3104

Throwing an Error should be only used in technical use cases and not for application logic.

Use a service to post a new 'error' and a directive, which will render there 'errors' - have a look at the Bootstrap alert module. There are hundreds and thousands of implementation on the internet. Pick the one which is right for you.

Upvotes: 0

Related Questions