Skip to content

Instantly share code, notes, and snippets.

@danharper
Last active August 29, 2015 14:16
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 danharper/011659366641d4ca85f7 to your computer and use it in GitHub Desktop.
Save danharper/011659366641d4ca85f7 to your computer and use it in GitHub Desktop.
ngComponent, ES6 classes for directives. Inspired by: https://github.com/angular/angular.js/issues/10007#issuecomment-77509179. Even more experimental version: https://gist.github.com/danharper/0ce7298d14b569ac3aa3
import ngComponent from 'ngComponent'
import SayingHelloComponent from './SayingHelloComponent'
angular.module('app', [])
.directive(...ngComponent(SayingHelloComponent))
import {ngBridge} from 'ngBridge'
import SayingHelloComponent from './SayingHelloComponent'
ngBridge(angular.module('app', []))
.component(SayingHelloComponent)
// using my "ngBridge" extension (https://gist.github.com/danharper/0ce7298d14b569ac3aa3)
export function ngComponent(name, component = null) {
if ( ! component) return ngComponent(null, name)
let ddo = component.ddo()
let directive = () => {
return {
...ddo,
scope: ddo.bind,
bindToController: true,
controller: [...getInjects(components), component],
controllerAs: ddo.name
}
}
return [(name || ddo.name), directive]
}
function getInjects(func) {
return func.ngInject ? func.ngInject() : []
}
export default class SayingHelloComponent {
static ngInject() {
return [] // register your dependencies here (Angular 1 style, with string names)
}
static ddo() {
return {
bind: {
person: '@'
},
name: 'sayingHello', // component's name
template: `<strong>{{sayingHello.greeting}}</strong> {{sayingHello.person}}!
<button ng-click="sayingHello.changeGreeting()">change greeting</button>`
}
}
constructor() { // you'll get your dependencies here like usual
this.possibleGreetings = ['hello', 'howdy', "g'day", 'hi', 'sup']
this.changeGreeting()
}
changeGreeting() {
this.greeting = rand(this.possibleGreetings)
}
}
function rand(items) {
return items[Math.floor(Math.random() * items.length)]
}
<saying-hello person="Dan"></saying-hello>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment