我的建议是将其封装在alertFactory
中,以便可以从任何地方使用:
App.factory('alertFactory',['$rootScope',
function($rootScope) {
var alertService = {};
$rootScope.alerts = [];
alertService.addAuto = function(type, msg, delay) {
var alert = {'type': type, 'msg': msg};
$rootScope.alerts.push(alert);
if (!delay ) {
delay = 2500;
}
window.setTimeout(function() {
var index = $rootScope.alerts.indexOf(alert);
if (index > -1) {
$rootScope.alerts.splice(index, 1);
$rootScope.$apply();
}
}, delay);
}
return alertService;
}])
将此内容放在您的 `index.html` 文件中,例如:
<script src="components/angular-ui-bootstrap-bower/ui-bootstrap-tpls.js"></script>
...
<alert ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</alert>
调用方式如下
App.controller('myCtrl', [ "alertFactory", function(alertFactory) {
var optionalDelay = 2500;
alertFactory.addAuto('success', 'my alert text', optionalDelay);
}]);