controller
We write a controller in a js file, such as app.js. We first declare a module like this:
1 |
angular.module('firstApp', []) |
then say, this module has a controller with this interface
1 |
.controller('mainController', function() { |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
angular.module('firstApp', []) .controller('mainController', function() { // bind this to vm (view-model) var vm = this; // define variables and objects on this // this lets them be available to our views // define a basic variable vm.message = 'Hey there! Come and see how good I look!'; // initial data vm.computers = [ { name: 'Macbook Pro', color: 'Silver', nerdness: 7 }, { name: 'Yoga 2 Pro', color: 'Gray', nerdness: 6 }, { name: 'Chromebook', color: 'Black', nerdness: 5 } ]; vm.computerData = {}; //init the variable //when form submits, it will call this function vm.addComputer = function() { //get our inited array of computers, and add it on vm.computers.push({ name: vm.computerData.name, color: vm.computerData.color, nerness: vm.computerData.nerdness }); //clear the variable vm.computerData = {}; //clear the varaible }; }); |
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:
1 |
<body class="container" ng-app="firstApp" ng-controller="mainController as main"> |
Then we access the mainController’s properties and property function definitions like so in the html page:
1 |
<h1>{{ main.message }} </h1> |
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 main.computerData.name as the model. Whatever text we put into our textfield, gets bound to mainController’s computerData object’s name property. Thus, main.computerData.name.
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.
1 2 3 4 5 6 7 8 9 10 |
<form class="form-inline" ng-submit="main.addComputer()"> <input type="text" class="form-control" placeholder="macbook" ng-model="main.computerData.name"> ......... <button type="submit" class="btn btn-success">Add</button> </form> |