Skip to content

Instantly share code, notes, and snippets.

@chiquitinxx
Created March 2, 2015 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save chiquitinxx/e0c561547e0e1b690767 to your computer and use it in GitHub Desktop.
Save chiquitinxx/e0c561547e0e1b690767 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