I'm using Twitter Bootstrap for UI in my webapp. Particulary its Alert component. I want to write a simple angular service to wrap Bootstrap's Alert to have a possibility of informing users from any peace of angular code. Like this:
Informer.inform("message", "ERROR"); // will result in alerting with `alert-error` class
Informer.inform("message", "INFO"); // will result in alerting with `alert-info` class
My idea is to to append the template to the end of the <body>
:
<div class="alert {{alertClass}} fade in informer" id="informer">
<button type="button" class="close" data-dismiss="alert">×</button>
<div class="valignCenterWrapper">
<div class="valignCenter" id="informerMessage">
{{message}}
</div>
</div>
</div>
Something like this:
grfx.factory("Informer", function() {
return {
inform : function(message, type) {
// Here be dragons. How can I compile/append the template.
$("#inform").alert();
}
};
});
The only thing I want to know: how do I write this with angular, not with jQuery? Is the code above good for start? Folks in the internets say that I should only use directives for DOM manipulation. But I do not understand it: I do not have any existing markup to apply directive on it. Alerts will be appended to the page as a result of some compupations/user interactions. Which services ($compile
, $parse
, $document
) should I use to compile temlate and append it somewhere to the body?
EDIT: Is it also possible to get angularjs service outside of controller. Just in regular JS code so I can write getServiece("Informer").inform("", "")
?
EDIT 2: Ok, what I have now:
grfx.factory("Informer", function($compile, $rootScope) {
return {
inform : function(message, type) {
var scope = $rootScope.$new();
scope.message = message;
scope.type = type;
$(document.body).append($compile("<div class='alert {{type}} fade in informer' id='informer'><button type='button' class='close' data-dismiss='alert'>×</button><div class='valignCenterWrapper'><div class='valignCenter' id='informerMessage'>{{message}}</div></div></div>")(scope));
}
};
});
With this code I am able to use injected service from controllers. But there is an issue when I try to call service outside angular code:
angular.element(document).injector().get("Informer").inform("Message", "alert-error");
This shows popup with {{message}}
e.g. it does not compile template correctly.