Angular-UI Bootstrap組件實現(xiàn)警報功能
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中的不同的控制器中創(chuàng)建警報,并且跨控制器的代碼不好引用,我們將要把它移到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屬性中調(diào)用service方法,我不清楚為什么不這樣來實現(xiàn)。
現(xiàn)在創(chuàng)建一個警報只需要從你的任何一個控制器中調(diào)用alertService.add()方法。
function ArbitraryCtrl($scope, alertService) { alertService.add("warning", "This is a warning."); alertService.add("error", "This is an error!"); }
總結(jié)
以上所述是小編給大家介紹的Angular-UI Bootstrap組件實現(xiàn)警報功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
淺談Angularjs中不同類型的雙向數(shù)據(jù)綁定
這篇文章主要介紹了淺談Angularjs中不同類型的雙向數(shù)據(jù)綁定,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07AngularJS實現(xiàn)表單手動驗證和表單自動驗證
本文是對AngularJS表單驗證,手動驗證或自動驗證的講解,對學習JavaScript編程技術(shù)有所幫助,感興趣的小伙伴們可以參考一下2015-12-12angularjs指令中的compile與link函數(shù)詳解
這篇文章主要介紹了angularjs指令中的compile與link函數(shù)詳解,本文同時訴大家complie,pre-link,post-link的用法與區(qū)別等內(nèi)容,需要的朋友可以參考下2014-12-12Angular 通過注入 $location 獲取與修改當前頁面URL的實例
這篇文章主要介紹了Angular 通過注入 $location 獲取與修改當前頁面URL的實例代碼,需要的朋友可以參考下2017-05-05angularjs select 賦值 ng-options配置方法
下面小編就為大家分享一篇angularjs select 賦值 ng-options配置方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02