Using Angular Forms With Controller As Syntax

I love using Angular's Controller As syntax to clean up my code, and I'm happy to see this technique is catching on.

Most of the time, I can avoid having to reference $scope altogether, but working with forms in Angular has always felt a little clunky to me. The FormController kind of just shoves itself into the $scope , leaving my controller with this ugly little reference.

var MyCtrl = function ( $scope ){ //Yucky reference to $scope in an otherwise // beautiful controller this . form = $scope . form ; };

Then a miracle happened!

Ok, so not a miracle, but after a bit of googling, I happened across this pull request from a year ago, which ended up being merged in here.

Awesome! but totally undocumented...

Now I can do this in my form:

<div ng-controller= "MyCtrl as ctrl" > <!-- Notice the 'ctrl' prefixing my form name? It's the same as my 'Controller As' alias --> <form name= "ctrl.form" > ... </form> </div>

And I now I can reference the form directly on my controller like this:

var MyCtrl = function (){ //Look mom! No $scope! }; MyCtrl . prototype . save = function (){ //Glorious $scope free access to FormController! if ( this . form . $valid ){ ... } };

And there you go.

One more way you can avoid Scope Soup and keep your controllers squeaky clean!