The Highly Anticipated Sequel to “A Little Bit of Angular in My Life”

Last week I published an introductory blog about AngularJS. I talked about initializing angular in your app and then promised to talk about controllers and directives in the next blog. Now, I fulfill that promise. Let’s start with controllers.

Controllers allow you to set the initial state of child scope, as well as add functionality to that scope. So let’s begin with controller declaration. We covered this a little bit last time but rather than send you back to my old post, I’ll quickly demonstrate my preferred method for creating a controller.

.controller(appCtrl, function() {};

We will fill in the function body later but for now we have initialized a new controller instance. There are two different syntax methods for manipulating scope. We will start with the standard one, $scope. Firstly we must pass our $scope into our controller as a parameter, like so:

.controller(appCtrl, function($scope) {};

This will give us access to variables on the $scope, which we can then modify, or use in functionality. Let’s say our app had an input field where the user needs to enter in their height. In our HTML page, we would insert the following code:

<div ng-controller="appCtrl"></div>

This gives our controller access to the scope of everything inside of this div. From there we would create an input field, and bind that to a model. The following text would go between the opening and closing div tags above.

<input ng-model="height">

Then in our controller we would create a $scope variable and initialize it with any value we want or none at all. In the function body, we would put:

$scope.height;

or

$scope.height = 6'0;

or any value we want. But how will our height get from our HTML to our controller. Well we should probably add a button to our HTML, although there are other possible solutions such as keydowns or keyups. But we are going with button here.

<button ng-click="setHeight(height)">Submit</button>

and in our controller we need to add that function we just invoked in our HTML.

$scope.setHeight = function(height) {$scope.height = height;};

Now when we type in our height, and click the submit button we’ve added, our $scope.height variable will be modified. Then we can display that in new set of tags like so

<span>{{height}}</span>

and our height will appear!

Now I will dubiously leave off here. Next time I will cover directives and controller as syntax. Thanks for reading!

Show your support

Clapping shows how much you appreciated Daniel Weill’s story.