Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.