Search code examples
javascriptangularjsangular-strap

Angular - how to do a dynamic alert with different type of errors?


In my web app I am showing alerts for loading content and another alert when there is an error.

I am using AngularJS/AngularStrap

right now this is what I have:

var noLinesAlert = $alert({
  title: 'Sorry, no lines at this moment :(',
  container: '.no-lines-alert',
  type: 'danger',
  dismissable: false,
  show: false
}),

loaderAlert = $alert({
  content: 'Loading content. Please wait...',
  container: '.alerts-container',
  type: 'info',
  show: true
  });

and I am calling these alerts this way, example noLinesAlert.show() or loaderAlert.hide() and so on... but just imagine that I will have 4 more alerts for special cases, do I have to create those vars with the object inside every time or is there a way to do it more programmatically? and how.


Solution

  • Well, you can store "default" settings for those 4 special cases in dedicated object, for example: ALERTS_SETTINGS = { notice: {} }, and then the call would be much more concise:

    var noticeOptions = angular.extend(ALERTS_SETTINGS.notice, { title: "My custom property one" })
    var notice = $alert(noticeOptions)
    

    Using angular.extend you can override any default setting from the original object by those you provide in the second argument.