Skip to content

Instantly share code, notes, and snippets.

@andrewstuart
Created December 2, 2015 22:01
Show Gist options
  • Save andrewstuart/934f23754f3db9bbb5af to your computer and use it in GitHub Desktop.
Save andrewstuart/934f23754f3db9bbb5af to your computer and use it in GitHub Desktop.
angular.module('app')
.directive('withService', function($injector) {
/**
* @ngdoc directive
* @name app.directive:withService
* @param {String} The name of the service to inject. May be
* an expression "X as Y" in which case the X service will be exposed by
* the name Y.
* @description Injects a service into a new scope the DOM element.
* @scope
* @restrict A
* @example
* <example module="withServiceExample">
* <file name="example.js">
* angular.module('withServiceExample', ['ngPortalApp'])
* .service('ExampleService', function() {
* this.foo = 'bar';
* });
* </file>
* <file name="example.html">
* <div with-service="ExampleService">
* ExampleService value of foo is: {{ExampleService.foo}}
* </div>
* <div with-service="ExampleService as es">
* ExampleService value of foo is: {{es.foo}}
* </div>
* </file>
* </example>
*/
return {
restrict: 'A',
scope: true,
link: function($scope, iEle, iAttrs) {
if ( !iAttrs.withService ) { return; }
var names = iAttrs.withService.split(' as ');
var scopePropName = names[1] || names[0];
var srv = $injector.get(names[0]);
if (srv) {
$scope[scopePropName] = srv;
}
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment