Using “Controller as” syntax in AngularJS

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Continuing directly from the last tutorial, we now use the “Controller as” syntax.  This eliminate the $scope parameter passing and hence is another way to solve the minification issue mentioned in last tutorial.

In one of our previous tutorial, we defined our controller with an injected $scope as parameter.

With AngularJs 1.2 or above, we can now define our controller like this …

no more $scope

no more $scope in parameter

No more needing to pass in $scope in the parameter.  And replace all $scope in the controller function with “this” keyword.

We then have to change our index.html file to use the “controller as” syntax…

using controller as syntax

using controller as syntax

But now all controller methods and properties, you have to prefix with the controller instance (in our case listCtrl).

This works just like before and will not break if you minify the JS file.  This method will be useful when there is multiple controllers in the same HTML as your app gets more complex.

 Ready for next tutorial?