Creating an AngularJS Controller
Wednesday 10 April 2013
- Getting started with AngularJS
- Creating an AngularJS Controller
- The AngularJS $scope is not the MVC Model
- Using repeating elements in AngularJS
- Filtering the data in an AngularJS ngRepeat element
- Using the AngularJS FormController to control form submission
- Creating an AngularJS Directive
In the previous blog post I showed how to get started with a really minimal AngularJS application. Even though the app could multiply two numbers it could hardly be called useful and as it turns out that is about as much as I could do with it.
Model View Controller
AngularJS is an MVC framework. So far we have only seen the View part as the HTML used was the view used to render the page to the user. As the name suggest there should be more in the form of a Controller and a Model.
The Controller part of an MVC application is normally the glue that ties a specific part of that application together. It gathers the data (Model) together and tells the View to render the data to the user. It also responds to events to do things.
Suppose we want to expand on the simple page from the previous post and turn this into a simple calculator, like in the screenshot below, the controller would be responsible for the calculations and the view would just be about displaying the data and not, like with the previous example, contain the actual calculation.
The AngularJS Controller
One special AngularJS thing is the $scope variable passed into the function and used.
What is the $scope?
The $scope variable is inserted automatically by AngularJS and serves as the bridge to share data between the controller and the view. Each variable added to the $scope is automatically be available for use in view data binding expressions. In fact there is always a scope, in the example from the previous the values where still stored in an AngularJS scope even though no controller was used.
The way AngularJS knows what to pass to the controller function is determined by the name. Just because we named it $scope AngularJS knows what to pass. This is done by a mechanism called dependency injection which is a very powerful mechanism used to separate different parts of the application and wire them up automatically at runtime while allowing us to pass in dummy services for testing purposes.
The AngularJS View
The view used is similar to the example from the previous blog post.
New is the ng-controller attribute that tells AngularJS to create the controller and what part of the HTML view it controls. In the view we don’t have to use the $scope variable, every expression is always evaluated scoped to the current $scope.
Testing the controller
One of the reasons for using an MVC framework is the capability to test the code. As the controller has no requirements for testing it should be easy enough to test it. Below is a test for adding two numbers using QUnit.