我的建議是把它包在一個alertFactory
,可以從任何地方使用:
App.factory('alertFactory',['$rootScope',
function($rootScope) {
var alertService = {};
$rootScope.alerts = [];
// will automatidally close
// types are success, warning, info, danger
alertService.addAuto = function(type, msg, delay) {
var alert = {'type': type, 'msg': msg};
$rootScope.alerts.push(alert);
if (!delay) {
delay = 2500; // default delay is 2500ms
}
window.setTimeout(function() {
var index = $rootScope.alerts.indexOf(alert);
if (index > -1) {
$rootScope.alerts.splice(index, 1);
$rootScope.$apply(); // refresh GUI
}
}, 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);
}]);
正常工作:http://plnkr.co/edit/0ovNkuePOra371EUzMge?p=preview – dfsq
是像我說的,有當無問題在一系列警報上使用ng-repeat。但我正在尋找一個單一的警報,正如你可以看到,如果你複製第一個代碼位,它不會在那裏工作。 – Klausette