Expressions in AngularJS are snippets of code that are usually written within double curly braces {{ }}
in HTML templates. These expressions are evaluated by AngularJS and replaced with their corresponding values or results in the rendered HTML.
-
Dynamic Content:
Expressions allow you to display dynamic data in HTML templates.
<p>Hello, {{ username }}!</p>
-
Simple JavaScript-Like Syntax:
Expressions support JavaScript-like syntax and basic operations.
<p>Total: {{ quantity * price }}</p>
-
Data Binding:
Expressions facilitate two-way data binding, meaning changes in the model are automatically reflected in the view and vice versa.
<input type="text" ng-model="username"> <p>Hello, {{ username }}!</p>
-
Usage with Directives:
Expressions are commonly used with AngularJS directives for manipulating the DOM based on evaluated expressions.
<div ng-show="isLoggedIn">Welcome, {{ username }}!</div>
- No Control Structures: Expressions are not meant to contain control structures like loops or conditionals. They are designed to be lightweight and are evaluated on the fly.
- No Global Variables: Expressions can access properties/methods from the scope but don't have access to global JavaScript objects or functions.
- Sanitization: AngularJS automatically sanitizes expressions to prevent injection attacks, ensuring security in the rendered output.
Consider a simple example demonstrating expressions and data binding:
<div ng-app="myApp" ng-controller="MyController">
<input type="text" ng-model="username">
<p>Hello, {{ username }}!</p>
</div>
angular.module('myApp', [])
.controller('MyController', ['$scope', function($scope) {
$scope.username = 'John';
}]);
In this example, the value entered in the input field (bound to $scope.username
) will be dynamically displayed in the paragraph (<p>Hello, {{ username }}!</p>) due to the AngularJS expression {{ username }}
.
Expressions in AngularJS provide a simple yet powerful way to create dynamic and data-driven HTML templates, making it easier to bind and display data from the model to the view.