PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

如何使用Angular-UI Bootstrap组件实现警报的方法

不言
不言 原创
2018-07-13 09:57:07 1641浏览

这篇文章主要介绍了关于如何使用angular-ui bootstrap组件实现警报的方法,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

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

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

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

view

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

controller

function AlertDemoCtrl($scope) {
  $scope.alerts = [
    { type: &#39;error&#39;, msg: &#39;Oh snap! Change a few things up and try submitting again.&#39; }, 
    { type: &#39;success&#39;, msg: &#39;Well done! You successfully read this important alert message.&#39; }
  ];
  $scope.addAlert = function() {
    $scope.alerts.push({msg: "Another alert!"});
  };
  $scope.closeAlert = function(index) {
    $scope.alerts.splice(index, 1);
  };
}

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

alertService

&#39;use strict&#39;;
/* services.js */
// don&#39;t forget to declare this service module as a dependency in your main app constructor!
var appServices = angular.module(&#39;appApp.services&#39;, []);
appServices.factory(&#39;alertService&#39;, function($rootScope) {
    var alertService = {};
    // create an array of alerts available globally
    $rootScope.alerts = [];
    alertService.add = function(type, msg) {
      $rootScope.alerts.push({&#39;type&#39;: type, &#39;msg&#39;: msg});
    };
    alertService.closeAlert = function(index) {
      $rootScope.alerts.splice(index, 1);
    };
    return alertService;
  });

view

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

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

controller

function RootCtrl($rootScope, $location, alertService) {
  $rootScope.changeView = function(view) {
    $location.path(view);
  }
  // root binding for alertService
  $rootScope.closeAlert = alertService.closeAlert; 
}
RootCtrl.$inject = [&#39;$scope&#39;, &#39;$location&#39;, &#39;alertService&#39;];

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

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

实例详解vue.js内置组件之keep-alive组件的使用

Angular5中提取公共组件之radio list的实例代码_AngularJS

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。