-
-
Save pmauduit/66402712bb5fa1a8b3e4 to your computer and use it in GitHub Desktop.
My trait approach to an angular.js controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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