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
For example: localhost:8080/myPageName
The definition of the controller will take place in the $routeProvider
section of the app.js
file.
Which will leave the .html
view without any ng-controller
property.
The rules in detail
- Except
$scope.$on
and a few special cases, we do not use the$scope
of that controller - Only the functions and variables needed in the view should be linked to the
vm
- 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
$inject
at the top of the component - Inside the controller, you call the public functions using
vm.nameOfTheFunction()