In this final example we take a look at some additional JavaScript interactions within the scope. As described previously, much of the JavaScript functionality is supported in AngularJS expression. To illustrate this better, the example shows some array manipulation as well as utilizing the JavaScript Math
object within expressions.
Listing 5.5 creates a simple AngularJS controller that contains two arrays in the scope. Notice that on line 3, the following statement adds a Math
variable to the scope by assigning it to windows.Math
. This is necessary to use the JavaScript Math
functionality because only the scope variables are available when AngularJS expressions are evaluated:
$scope.Math = window.Math;
Listing 5.6 implements an AngularJS template that uses AngularJS expressions to display the arrays, show the array length, as well as manipulate the array elements using push()
and shift()
directly in the expressions. Note that because we have added Math
to the scope, we are able to use JavaScript Math
operations directly in the expressions in lines 16 and 23.
Figure 5.3 shows the AngularJS web page rendered. Notice that as the links are clicked, the arrays get adjusted and the expressions are reevaluated.
01 angular.module('myApp', [])
02 .controller('myController', function($scope) {
03 $scope.Math = window.Math;
04 $scope.myArr = [1];
05 $scope.removedArr = [];
06 });
01 <!doctype html>
02 <html ng-app="myApp">
03 <head>
04 <title>AngularJS Expressions</title>
05 <style>
06 a{color: blue; text-decoration: underline; cursor: pointer}
07 </style>
08 </head>
09 <body>
10 <div ng-controller="myController">
11 <h1>Expressions</h1>
12 Array:<br>
13 {{myArr}}<hr>
14 Elements removed from array:<br>
15 {{removedArr}}<hr>
16 <a ng-click="myArr.push(Math.floor(Math.random()*100 + 1))">
17 Click to append a value to the array</a><hr>
18 <a ng-click="removedArr.push(myArr.shift())">
19 Click to remove the first value from the array</a><hr>
20 Size of Array:<br>
21 {{myArr.length}}<hr>
22 Max number removed from the array:<br>
23 {{Math.max.apply(Math, removedArr)}}<hr>
24 <script src="http://code.angularjs.org/1.3.0/angular.min.js"></script>
25 <script src="js/expressions_javascript.js"></script>
26 </body>
27 </html>