You'll revisit these!
Controllers are JS constructor functions that set up the $scope object and add behavior to the $scope
Controllers DO:
Controllers manage the business logic of your view
Controllers DO NOT:
const app = angular.module("app", [])
app.controller("ShoppingController", function($scope) {
// This is your constructor function. Anything you
// do here should be bootstrapping the initial state
// of your app
// Anything added to the $scope object is available
// to the view
$scope.boundValue = "Initial Value for boundValue";
});
What is a controller?
Where would we use a controller?
Now, spend the next 3 minutes and answer these two questions:
<body ng-app="spicyApp">
<div ng-controller="SpicyController">
<input ng-model="customSpice">
<button ng-click="spicy('chili')">Chili</button>
<button ng-click="spicy(customSpice)">Custom spice</button>
<p>The food is {{spice}} spicy!</p>
</div>
</body>
index.html
var myApp = angular.module('spicyApp', []);
myApp.controller('SpicyController', function($scope) {
$scope.customSpice = 'wasabi';
$scope.spice = 'very';
$scope.spicy = function(spice) {
$scope.spice = spice;
};
});
app.js
Build an angular app with a single HTML page and with a single app.js file that has one controller.
Use the controller and $scope to bind to a an input and display that input on the page
Stretch goal: explore ng-style in the angular docs, how can you implement it in this app?
$scope is used to expose our js functions and data to the view, our HTML
This means that $scope acts as the go-between for the model and the view
Scope is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can watch expressions and propagate events.
Also! It's just a JavaScript Object, you can attach methods and properties to it.
A significant problem that developers new to Angular encounter is that attaching primitive values to $scope breaks the 2-way data binding a LOT.
If you do this, you will save yourself COUNTLESS HOURS trying to debug.
So always assign all $scope primitives to an object that is bound to $scope.
// Don't do this:
$scope.somePrimitive = 5;
// Instead, always always always do this:
$scope.view = {};
$scope.view.somePrimitive = 5;
Custom and some built-in directives also create scope in angular, which you'll need to watch out for.
These directives create their own scope context! You'll also create custom directives that create their own scope.
Some built-in directives that create scope include:
Spend 4 minutes writing about scope and controllers, answer these questions:
First: Read the intro to controllers markdown in the Angular curriculum and do the exercises.
Second: Work on the Ca$h Register assignment for Thursday
The intro to $scope article in the Angular curriculum is a good resource to learn more about $scope, if you are interested read that.