How to Write a Controller
Our main rule regarding writing a controller, is to use the
Controller as vm style, however, we also have a few other style guidelines.
You can see below a full example of what the controller would look like.
This might look like a lot of lines, but it is mainly to show all the rules at once.
Using the controller in a view
Now let's see how we can use it inside our
.html view in normal situations.
Using the controller in a page
In the case where your controller will be used on a view directly linked to a route
The definition of the controller will take place in the
$routeProvider section of the
Which will leave the
.html view without any
The rules in detail
$scope.$onand a few special cases, we do not use the
$scopeof that controller
- Only the functions and variables needed in the view should be linked to the
- The view is using the controller's variables and functions through the 'as' keyword you set
- Private functions' name start with a
- Functions and variables are grouped by type in that order: private variables, public variables, init function call, public functions, private functions, $scope.$on functions
- There is a nice comment separating all those groups
- Services are added to the controller using the
$injectat the top of the component
- Inside the controller, you call the public functions using