Created
February 3, 2014 08:22
-
-
Save dansimco/8780440 to your computer and use it in GitHub Desktop.
Angular Directive as a Service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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