Angular controllers


We write a controller in a js file, such as app.js. We first declare a module like this:

then say, this module has a controller with this interface

mainController is this controller’s type. We’ll use type and declare a variable in an html file somewhere and thus, that front end html file gets to access the properties and function definitions as defined in this controller.

In our example, we have:

  • property variable called message
  • an array of objects called computers
  • an add function where we use the array computers and push another object onto this array

front end

We use a controller in Angular were we declare a controller name such as mainController, then declare a variable with it, such as main like so:

Then we access the mainController’s properties and property function definitions like so in the html page:

we have also call controller property functions and bind HTML data to controller property variables.

For example, the name data from our input gets bound to the lone object computerData variable in our controller. We bind it by declaring as the model. Whatever text we put into our textfield, gets bound to mainController’s computerData object’s name property. Thus,

The addComputer function gets called, the data are bound. Then the function definition uses array function push to push the computerData object onto the computers array. Then it clears the computerData object to ready for the next bind.