Skip to content

Instantly share code, notes, and snippets.

@pmauduit
Forked from chiquitinxx/gist:e0c561547e0e1b690767
Created November 27, 2015 11:37
Show Gist options
  • Save pmauduit/66402712bb5fa1a8b3e4 to your computer and use it in GitHub Desktop.
Save pmauduit/66402712bb5fa1a8b3e4 to your computer and use it in GitHub Desktop.
My trait approach to an angular.js controller
//Grooscript Angular.js TODO example from https://angularjs.org/
//You need next release of grooscript to run it (1.0.1)
class TodoController implements AngularController {
def todos = [
[text:'learn angular', done: true],
[text:'build an angular app', done: false]
]
def addTodo() {
scope.todos << [text: scope.todoText, done: false]
scope.todoText = ''
}
def remaining() {
scope.todos.count { it.done }
}
def archive() {
scope.todos = todos.findAll { !it.done }
}
}
trait AngularController {
def scope
Closure init() {
{ controller, angularScope ->
controller.scope = angularScope
controllerProperties(controller).each { nameProperty ->
angularScope."$nameProperty" = controller."$nameProperty"
}
controllerMethods(controller).each { nameMethod ->
angularScope."$nameMethod" = controller.&"$nameMethod"
}
}.curry(this)
}
static controllerProperties(controller) {
controller.properties.findAll { key, value ->
!(key in ['class', 'scope'])
}.collect { key, value -> key }
}
static controllerMethods(controller) {
controller.metaClass.methods.findAll { method ->
!method.name.startsWith('set') && !method.name.startsWith('get') && !method.name.contains('$') &&
!(method.name in ['equals', 'hashCode', 'notify', 'notifyAll', 'toString',
'wait', 'controllerMethods', 'controllerProperties', 'init',
'invokeMethod'])
}.collect { it.name }
}
}
//Using it in javascript with angular
//angular.module('todoApp', []).controller('TodoController', ['$scope', TodoController().init()]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment