AngularJS expressions can be written within double braces: {{ expression }}
or included in a directive using ng-bind="expression"
. AngularJS evaluates the expression and displays the result at the designated location, and similar to JavaScript, these expressions can include literals, operators, and variables.
For example, {{ 5 + 5 }} or {{ firstName + ” ” + lastName }}.
<!DOCTYPE html> <html> <script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js”></script> <body> <div ng-app=””> <p>My first expression: {{ 5 + 5 }}</p> </div> </body> </html> |
If you remove the ng-app directive, the HTML will display the expression exactly as it is, without evaluating it.
<!DOCTYPE html> <html> <script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js”></script> <body> <div> <p>My first expression: {{ 5 + 5 }}</p> </div> </body> </html> |
You can place expressions anywhere in your HTML, and AngularJS will evaluate and return the results. For example, AngularJS can modify CSS properties, allowing you to change the color of the input box below by adjusting its value.
lightblue |
<div ng-app=”” ng-init=”myCol=’lightblue'”> <input style=”background-color:{{myCol}}“ ng-model=”myCol”> </div> |
AngularJS numbers are similar to JavaScript numbers.
<div ng-app=”” ng-init=”quantity=1;cost=5″> <p>Total in dollar: {{ quantity * cost }}</p> </div> |
The same example can be implemented using ng-bind:
<div ng-app=”” ng-init=”quantity=1;cost=5″> <p>Total in dollar: <span ng-bind=”quantity * cost”></span></p> </div> |
Using ng-init is not very common; you’ll discover a more effective method for initializing data in the chapter on controllers. |