SoFunction
Updated on 2025-04-13

Angular-UI Bootstrap component implements alert function

Angular-UI Bootstrap provides many components, porting from popular Bootstrap projects to Angular directives (significantly reducing the amount of code). If you plan to use the Bootstrap component in your Angular application, I recommend checking it carefully. Having said that, using Bootstrap directly should work.

Angular controller can share the service's code. Alerts are one of the good use cases for sharing service code to controllers.

The Angular-UI Bootstrap documentation provides the following examples:

view

<div ng-controller="AlertDemoCtrl">
 <alert ng-repeat="alert in alerts" type="" close="closeAlert($index)">{{}}</alert>
 <button class='btn' ng-click="addAlert()">Add Alert</button>
</div>

controller

function AlertDemoCtrl($scope) {
 $ = [
  { type: 'error', msg: 'Oh snap! Change a few things up and try submitting again.' }, 
  { type: 'success', msg: 'Well done! You successfully read this important alert message.' }
 ];

 $ = function() {
  $({msg: "Another alert!"});
 };

 $ = function(index) {
  $(index, 1);
 };
}

Given that we are going to create an alert in different controllers in the app and the code across the controller is not easy to reference, we are going to move it into the service.

alertService

'use strict';
/*  */
// don't forget to declare this service module as a dependency in your main app constructor!
var appServices = ('', []);
('alertService', function($rootScope) {
  var alertService = {};
  // create an array of alerts available globally
  $ = [];
   = function(type, msg) {
   $({'type': type, 'msg': msg});
  };
   = function(index) {
   $(index, 1);
  };
  return alertService;
 });

view

<div>
 <alert ng-repeat="alert in alerts" type="" close="closeAlert($index)">{{  }}</alert>
</div>

Finally, we need to bind the closeAlert() method in alertService's to $globalScope.

controller

function RootCtrl($rootScope, $location, alertService) {
 $ = function(view) {
  $(view);
 }
 // root binding for alertService
 $ = ; 
}
RootCtrl.$inject = ['$scope', '$location', 'alertService'];

I don't quite agree with this global binding, what I want is to call the service method directly from the close data property in the alert directive, I'm not sure why it doesn't do this.

Now creating an alert requires just calling the() method from any of your controllers.

function ArbitraryCtrl($scope, alertService) {
 ("warning", "This is a warning.");
 ("error", "This is an error!");
}

Summarize

The above is the Angular-UI Bootstrap component that the editor introduced to you to implement the alarm function. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!