var app = angular.module('plunker', ['ui.bootstrap']);
app.controller('FirstCtrl', function($scope, alertService, $timeout) {
$scope.alertService = alertService;
alertService.addAlert({"type": "info", "msg": "Infomessage I"});
$scope.name = 'World';
});
app.controller('SecondCtrl', function($scope, alertService, $timeout) {
$scope.alertService = alertService;
alertService.addAlert({"type": "info", "msg": "Infomessage Second"});
$scope.name = 'World Second';
});
app.service('alertService', function($timeout) {
var service = {};
var timeout;
// start with empty array holding the alerts.
service.alert_list = [];
// method to add an alert
// alert_obj is a object with members type = ( success | info | warning | danger )
// and msg which is the message string
service.addAlert = function (alert_obj) {
service.alert_list = [];
service.alert_list.push(alert_obj);
$timeout.cancel(timeout);
timeout = $timeout(service.clearAlerts, 5000);
};
service.clearAlerts = function clearAlerts() {
service.alert_list = [];
};
return service;
});
app.directive('tqAlertlist', function tqAlertlist() {
return {
scope: {
alerts: '=',
},
restrict: 'E',
templateUrl: 'tq-alertlist.html',
replace: true,
};
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link data-require="bootstrap-css@*" data-semver="3.0.3" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" />
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.0.x" src="http://code.angularjs.org/1.2.10/angular.js" data-semver="1.2.10"></script>
<script data-require="ui-bootstrap@*" data-semver="0.10.0" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.10.0.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="container">
<h1>Service demo</h1>
<div class="row">
<div class="col-xs-6" ng-controller="FirstCtrl">
<tq-alertlist alerts="alertService.alert_list"></tq-alertlist>
<p>Hello {{name}}!</p>
</div>
<div class="col-xs-6" ng-controller="SecondCtrl">
<tq-alertlist alerts="alertService.alert_list"></tq-alertlist>
<p>Hello {{name}}!</p>
</div>
</div>
</div>
</body>
</html>
<alert ng-repeat="alert in alerts" type="alert.type">
<div class="clearfix">
<span class="pull-left">{{alert.msg}}</span>
<pie-timer></pie-timer>
</div>
</alert>