SO - Directive with Service
Example of communicating to a directive via a service.
by Jeremy Likness
HTML
<div ng-app="myApp" ng-controller="myController">
<div id="example"></div>
<div j-query-directive=""></div>
</div>
JavaScript
var app = angular.module("myApp", []);
app.service("directiveService", function() {
var listeners = [];
return {
subscribe: function(callback) {
listeners.push(callback);
},
publish: function(msg) {
angular.forEach(listeners, function(value, key) {
value(msg);
});
}
};
});
app.directive("jQueryDirective", function(directiveService) {
directiveService.subscribe(function(msg) {
// pretend this is jQuery
document.getElementById("example")
.innerHTML = msg;
});
return {
restrict: 'E'
};
});
app.controller("myController", function(directiveService) {
directiveService.publish("This is a test.");
});