AngularJS Expressions

Last article explained AngularJS directives in detail. This article focuses on AngularJS Expressions. In AngularJS, expressions are written inside double curly opening and closing brackets i.e. {{expression}}. You can also write an expression in AngularJS inside the “ng-bind” directive i.e. ng-bind=”expression”. Anything in the expression is evaluated by AngularJS which returns the result of the expression. Expressions in AngularJS are quite similar to JavaScript expressions. You can use literal values, operators and variables inside expressions. Take a look at our first example of AngularJS expressions.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="">
    <p>{{3 *5}}</p>
 	<p ng-bind="3*5"></p>
    
</div>

</body>
</html>

Download the code Try the code

In the above example both ng-bind and doubly curly brackets contain an expression which multiplies 3 and 5. If you open the above webpage in browser, you will see 15 displayed twice in the output.

Now if you try to remove the “ng-app” attribute from the div, and then execute AngularJS expression inside the div, you will see that the page shall display “{{3 * 5}}”.

Changing Style Via AngularJS Expressions

AngularJS expressions can change script as well as style associated with any html element. Take a look at the following example to see how to change text color of a paragraph via AngularJS expressions.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="" ng-init="textcolor='pink'">

<input type="text" ng-model="textcolor">

<p style="color:{{textcolor}}">The color of this text changes as specified in text box.</p>

</div>

</body>
</html>

Download the code Try the code

Open the above page in the browser. You will see a text box with text “pink”. Below the text box there should be paragraph with pink text. Now change the text inside the paragraph from pink to blue. You will see the color of the text inside the paragraph turn blue. This is because we initialized an AngularJS variable “textcolor” and assigned it value of color. Then using ng-model this application variable was bound to the input value of the text box. Finally, for the paragraph style, we specified that its color should be equal to the value of the AngularJS application variable “textcolor”. Therefore, changing the color name in the text box updated the text color of the paragraph.

<<< AngularJS DirectivesAngularJS Data Types >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .