当前位置:Gxlcms > JavaScript > Angular-UI Bootstrap组件实现警报功能

Angular-UI Bootstrap组件实现警报功能

时间:2021-07-01 10:21:17 帮助过:3人阅读

Angular-UI Bootstrap提供了许多组件,从流行的的Bootstrap项目移植到Angular 指令(显著的减少了代码量)。如果你计划在Angular应用中使用Bootstrap组件,我建议细心检查。话虽如此,直接使用Bootstrap,应该也是可以工作的。

Angular controller可以共享service的代码。警报就是把service代码共享到controller的很好用例之一。

Angular-UI Bootstrap文档提供了下面的例子:

view

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

controller

  1. function AlertDemoCtrl($scope) {
  2. $scope.alerts = [
  3. { type: 'error', msg: 'Oh snap! Change a few things up and try submitting again.' },
  4. { type: 'success', msg: 'Well done! You successfully read this important alert message.' }
  5. ];
  6. $scope.addAlert = function() {
  7. $scope.alerts.push({msg: "Another alert!"});
  8. };
  9. $scope.closeAlert = function(index) {
  10. $scope.alerts.splice(index, 1);
  11. };
  12. }

鉴于我们要在app中的不同的控制器中创建警报,并且跨控制器的代码不好引用,我们将要把它移到service中。

alertService

  1. 'use strict';
  2. /* services.js */
  3. // don't forget to declare this service module as a dependency in your main app constructor!
  4. var appServices = angular.module('appApp.services', []);
  5. appServices.factory('alertService', function($rootScope) {
  6. var alertService = {};
  7. // create an array of alerts available globally
  8. $rootScope.alerts = [];
  9. alertService.add = function(type, msg) {
  10. $rootScope.alerts.push({'type': type, 'msg': msg});
  11. };
  12. alertService.closeAlert = function(index) {
  13. $rootScope.alerts.splice(index, 1);
  14. };
  15. return alertService;
  16. });

view

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

最后,我们需要将alertService's中的closeAlert()方法绑定到$globalScope。

controller

  1. function RootCtrl($rootScope, $location, alertService) {
  2. $rootScope.changeView = function(view) {
  3. $location.path(view);
  4. }
  5. // root binding for alertService
  6. $rootScope.closeAlert = alertService.closeAlert;
  7. }
  8. RootCtrl.$inject = ['$scope', '$location', 'alertService'];

我不完全赞同这种全局绑定,我希望的是直接从警报指令中的close data属性中调用service方法,我不清楚为什么不这样来实现。

现在创建一个警报只需要从你的任何一个控制器中调用alertService.add()方法。

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

总结

以上所述是小编给大家介绍的Angular-UI Bootstrap组件实现警报功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

人气教程排行