AngularJS: Dependancy Sharing
Sharing dependancies between controllers and directives
by Matthew Marcus
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<div ng-controller="MyCtrl">Hello, {{name}}!
<doit></doit>
</div>
JavaScript
var myApp = angular.module('myApp', ['UICommon']);
var UICommon = angular.module('UICommon', [])
.service('SomeService', function () {
this.doIt = function(v){return 2 * v;};
})
.directive('doit', function (SomeService) {
return {
restrict: 'E',
link: function (scope, elem, attrs) {
console.log(SomeService.doIt(9));
}
};
});
angular.module('myApp').controller('MyCtrl', function ($scope, SomeService) {
$scope.name = 'Superhero';
console.log(SomeService.doIt(4));
});