Example kotlin controller in AngularJS


as an experiment I tried creating a controller in AngularJS using Kotlin.

At least it works even though it doesn't do very much :)

I guess its no surprise that the kotlin code is a little clunky, due to the $scope escaping due to $ being not allowed on identifiers and having to use the [“functionName”] subscript operators to define functions on the scope object but at least it shows it can be done. Here’s how the code would look in javascript (would look a bit neater still in typescript with the () => syntax for function declarations)

var myApp = angular.module("myApp", []); myApp.controller("ProductController", function($scope) {   $scope.clear = function() {   console.log("Cleared!");   };   $scope.save = function() {   console.log("Saved!");   }; });


You should be able to use the native-annotation to specify what the generated variable name is:

fun MyCtrl(native("$scope") scope: MyScope) { ... }

This way your code can access the scope without backticks.

I also tried integrating Kotlin with AngularJS (see my repository) and the simple scenarios (todo.kt) were quite easy to handle. I took the approach of writing native traits for my interfaces so that I get static typing and I don’t have to pollute my code with subscript-operators. All in all, I quite like the the result.

However, in the backend-example things didn’t go that smoothly. The original JavaScript example injected an object (Project) which was used as a constructor for instantiating new instances (i.e. new Project(…)) and as a namespace for some static data access methods (e.g. Project.query()). I couldn’t find a way to make that work in Kotlin without resorting to ugly hacks (natively implemented instantiateProject called from Kotlin.)

Finally I decided that AngularJS depends so heavily on the idiosyncrasies of JavaScript that I gave up trying to use it.