Skip to content

Instantly share code, notes, and snippets.

@dansimco
Created February 3, 2014 08:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dansimco/8780440 to your computer and use it in GitHub Desktop.
Save dansimco/8780440 to your computer and use it in GitHub Desktop.
Angular Directive as a Service
angular.module('MyComponent', [])
.service('MyComponent', function($log, $rootScope, $compile) {
return function(params) {
var scope;
// Pass params through to a new'd up scope.
// I'm just shoving them all in there as a property
// but you could be more discreet.
scope = $rootScope.$new();
scope.params = params;
var directive = $compile('<my-component>')(scope);
return scope;
}
})
.directive('myComponent', function() {
return {
restrict: 'E',
controller: 'MyComponent',
template: '<h2>My Component</h2>', //I usually pass these in via a JST var
replace: true,
};
})
.controller('MyComponent', function($scope, $log, $element) {
// $scope.params are available
$log.log('my component!', $scope.params);
//You may wish to hook the $element back so it's accessible externally
$scope.$element = $element;
});
//Demo
angular.module('app', ['MyComponent']).controller('TestCtrl', function(MyComponent, $log) {
var component = MyComponent({
foo: 'bar'
});
$log.log(component.$element);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment