Angular Zen
For example, one could create a getter function for the name variable, as given
in the following code:
var HelloCtrl = function ($scope) {
$scope.getName = function() {
return $scope.name;
};
}
And then use it in a template as given in the following code:
<h1>Hello, {{getName()}}!</h1>
The $scope object allows us to control precisely which part of the domain model
and which operations are available to the view layer. Conceptually, AngularJS
scopes are very close to the ViewModel from the MVVM pattern.
Controller
The primary responsibility of a controller is to initialize scope objects. In practice,
the initialization logic consists of the following responsibilities:
- Providing initial model values
- Augmenting $scope with UI-specific behavior (functions)
Controllers are regular JavaScript functions. They don't have to extend any
framework-specific classes nor call any particular AngularJS APIs to correctly
perform their job.
Please note that a controller does the same job as the ng-init
directive, when it comes to setting up initial model values.
Controllers make it possible to express this initialization logic
in JavaScript, without cluttering HTML templates with code.
Model
AngularJS models are plain, old JavaScript objects. We are not obliged to extend
any of the framework's base classes nor construct model objects in any special way.
It is possible to take any existing, pure JavaScript classes or objects and use them
in the same way as in the model layer. We are not limited to model properties being
represented by primitive values (any valid JavaScript object or an array can be used).
To expose a model to AngularJS you simply assign it to a $scope.