简体   繁体   中英

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.

For every alert the title, container, type, and show property changes. You need to give the program that information, so you can't do this any shorter.

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.

Make it dynamic by putting the $alert into a function. Allow the function to pass parameters to the $alert. Set the show property to true.

Call the function when needed. For example:

var displayAlert = function(alertTitle, className) {

    var alertOptions = {
       title: alertTitle,
       container: className,
       type: 'danger',
       dismissable: false,
       show: true
    };

    var alert = $alert(alertOptions);

}

// Call the function when needed
$scope.displayAlert('Sorry, no lines at this moment :(','.no-lines-alert')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM