Skip to content

Instantly share code, notes, and snippets.

@demetriusnunes
Created December 18, 2015 18:49
Show Gist options
  • Save demetriusnunes/2eafead8242ca2811a2d to your computer and use it in GitHub Desktop.
Save demetriusnunes/2eafead8242ca2811a2d to your computer and use it in GitHub Desktop.
Concise component definition for AngularJS 1.x
'use strict';
angular.module('Component', [])
.factory('Component', function () {
return function(bindings, template, linkFn, options) {
var directive = {
scope: parseBindings(bindings),
template: parseTemplate(template),
link: linkFn
};
return angular.extend({}, directive, options);
};
function parseBindings(bindings) {
return bindings.reduce(function(scope, binding) {
var name = binding.slice(1);
scope[name] = binding.slice(0, 1);
return scope;
}, {});
}
function parseTemplate(template) {
return angular.isArray(template) ? template.join('') : template;
}
});
'use strict';
angular.module('app', ['Component'])
.directive('personItem', function (Component) {
return Component(
['@name', '@age', '@highlight', '&onClick'],
['<div ng-click="onClick($event)"',
' ng-class="{ highlight: highlight === \'true\' }">',
' <h1>{{:: name}}</h1>',
' <p>{{:: age }}</p>',
'</div>']);
});
@demetriusnunes
Copy link
Author

PersonItem is a typical dumb component, but if need be, the optional 3rd and 4th parameters can be used to make it smart.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment