angular-classy, by @DaveJ, is an interesting AngularJS module that you use to get some class structure into your controller. You can check out his page and the documentation there for some basic examples of that it does.
This appeals to me as a Python developer because now my angular code looks more like a Python class. I also like that there's an init
function now (similar to python's __init__
I guess) and I also like that you can distinguish between "scope functions" and "local functions". To explain that, consider this:
// somewhere in a controller
...
$scope.addSomething = function() { // used in your template
if ($scope.some_precondition) {
reallyAddSomething($scope.firt_name, $scope.last_name);
}
};
function reallyAddSomething(first_name, last_name) {
// can still use $scope in here
}
And compare this with angular-classy:
// somewhere in a controller
...
addSomething: function() { // used in your template
if (this.$scope.some_precondition) {
this._reallyAddSomething(this.$scope.first_name, this.$scope.last_name);
}
},
_reallyAddSomething = function(first_name, last_name) {
// can still use this.$scope in here
},
Basically, the _
prefix makes the function available on this
but not attached to the scope. And I think that just makes sense!
So my guttural feeling is all positive about angular-classy. But there is still one big caveat. The mythical "this" in Javascript. It's great but it's kinda clunky too because it rebinds in every sub-scope. The solution to that is to bind things. For example, for a success
promise it now has to look like this:
this.$http.get('/some/url')
.success(function(response) {
this.somethingElseInTheModule(response.something);
}.bind(this));
Anyway, let's compare the before and after of a real project.
Before
After
What do you think? Does it look better? Full diff here
I think I like it. But I need to let it "sink in" a bit first. I think the code looks neater with angular-classy but it's now a new dependency and it means that people who know angular but not familiar with angular-classy would get confused when they are confronted with this code.
UPDATE
I merged the branch. So now this project is classy.
Comments