Skip to content

Instantly share code, notes, and snippets.

@wolever
Created May 6, 2015 23:09
Show Gist options
  • Save wolever/1024e1ee4ac510d4b2af to your computer and use it in GitHub Desktop.
Save wolever/1024e1ee4ac510d4b2af to your computer and use it in GitHub Desktop.
ezdirective makes it possible to create AngularJS directives without checking the documentation.
/*
* ezdirective makes it possible to create AngularJS directives without
* checking the documentation.
*
* Sane defaults are used (`restrict: 'E'` and `scope: {}`), and the link()
* function is injected using $injector, which which can also inject the
* `$scope`, `$elem`, and `attrs` that a normal directive link function would
* expect.
*
* Examples:
*
* // <url-loader url='/foo/bar'></url-loader>
* app.directive('url-loader', ezdirective({
* link: function(elem, attrs, $http) {
* $http.get(attrs.url)
* .success(function(result) {
* elem.textContent = result;
* });
* .error(function() {
* elem.textContent = "Error loading :(";
* })
* },
* }));
*
* // <hello-world name="{{ someName }}"></hello-world>
* app.directive('helloWorld', ezdirective({
* template: '<div class="hello-world">Hello, {{ name }}. It is {{ time }}!</div>',
* scope: {
* name: '@',
* },
* link: function($scope, $interval) {
* $scope.time = new Date();
* var interval = $interval(function() {
* $scope.time = new Date();
* });
* $scope.on('$destroy', function() {
* $interval.cancel(interval);
* });
* },
* });
*
* Reminders for the magic scope characters:
* @: {{ interpolable }} string: greeting="Hello, {{ name }}"
* =: two-way bound data: ng-model="mymodel.foo"
* &: lazily evaluated function: callback="myCallback()"
*/
var angular = require('angular');
module.exports = function(directive) {
var defaults = {
scope: {},
restrict: 'E',
};
return function($injector) {
var result = angular.extend(defaults, directive);
result.replace = (
result.replace !== undefined?
result.replace :
!!(result.template || result.templateUrl)
);
var link = result.link;
if (link) {
result.link = function($scope, elem, attrs) {
return $injector.invoke(link, this, {
$scope: $scope,
scope: $scope,
elem: elem,
attrs: attrs,
});
};
}
return result;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment