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='btn' ng-click="addAlert()">Add Alert</button></div>
controller
function AlertDemoCtrl($scope) { $scope.alerts = [ { 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.' } ]; $scope.addAlert = function() { $scope.alerts.push({msg: "Another alert!"}); }; $scope.closeAlert = function(index) { $scope.alerts.splice(index, 1); };}
鑒于我們要在app中的不同的控制器中創建警報,并且跨控制器的代碼不好引用,我們將要把它移到service中。
alertService
'use strict';/* services.js */// don't forget to declare this service module as a dependency in your main app constructor!var appServices = angular.module('appApp.services', []);appServices.factory('alertService', function($rootScope) { var alertService = {}; // create an array of alerts available globally $rootScope.alerts = []; alertService.add = function(type, msg) { $rootScope.alerts.push({'type': type, 'msg': 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 = ['$scope', '$location', 'alertService'];
我不完全贊同這種全局綁定,我希望的是直接從警報指令中的close data屬性中調用service方法,我不清楚為什么不這樣來實現。
現在創建一個警報只需要從你的任何一個控制器中調用alertService.add()方法。
function ArbitraryCtrl($scope, alertService) { alertService.add("warning", "This is a warning."); alertService.add("error", "This is an error!");}
總結
以上所述是小編給大家介紹的Angular-UI Bootstrap組件實現警報功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答