Once the controller has been defined, you can implement the scope, which involves linking HTML elements to scope variables, initializing the variables in the scope, and providing functionality to handle changes to the scope values.
Lines 9 and 10 in Listing 20.2 are <input>
elements that are assigned to the first
and last
values in the scope. These elements provide a method to update the scope from the browser. If the user types in the input, the scope is also updated:
09 <input type="text" ng-model="first">
10 <input type="text" ng-model="last">
Lines 3–5 in Listing 20.3 show the initial values of the scope being defined:
03 $scope.first = 'Some';
04 $scope.last = 'One';
05 $scope.heading = 'Message: ';
Line 11 in Listing 20.2 links a click handler to the updateMessage()
function defined in the scope:
11 <button ng-click='updateMessage()'>Message</button>
Lines 6–8 in Listing 20.3 show the updateMessage()
definition in the scope:
06 $scope.updateMessage = function() {
07 $scope.message = 'Hello ' + $scope.first +' '+ $scope.last + '!';
08 };
Line 13 implements an expression that displays the value of the heading
and message
variables in the scope on the HTML page:
13 {{heading + message}}
01 <!doctype html>
02 <html ng-app="firstApp">
03 <head>
04 <title>First AngularJS App</title>
05 </head>
06 <body>
07 <div ng-controller="FirstController">
08 <span>Name:</span>
09 <input type="text" ng-model="first">
10 <input type="text" ng-model="last">
11 <button ng-click='updateMessage()'>Message</button>
12 <hr>
13 {{heading + message}}
14 </div>
15 <script src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
16 <script src="/js/first.js"></script>
17 </body>
18 </html>
01 var firstApp = angular.module('firstApp', []);
02 firstApp.controller('FirstController', function($scope) {
03 $scope.first = 'Some';
04 $scope.last = 'One';
05 $scope.heading = 'Message: ';
06 $scope.updateMessage = function() {
07 $scope.message = 'Hello ' + $scope.first +' '+ $scope.last + '!';
08 };
09 });