Expressions in AngularJS


      AngularJS expressions bind application data to HTML. So how do you make AngularJS understand that you are writing an expression ? We need to specify expressions within curly braces as shown below :
Syntax : {{Expression}}

This in one way of writing expressions. Another way is to write expressions within ng-bind directive as follows
Syntax : ng-bind="expression"

Let see a simple example to understand this.

Writing Expression inside double curly braces

       AngularJS expressions are much like JavaScript expressions: They can contain literals, operators, and variables. You can write expressions wherever you like, AngularJS will simply resolve the expression and return the result.


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

<div ng-app>
<p>Simple Expression: </p>
<p>{{ 3 + 3 }}</p>
</div>

</body>
</html>

Hope the above example is self explanatory, it gives the output as shown below


Writing Expression inside ng-bind

       The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.


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

<div ng-app="myapp" ng-controller="myController">
  <label>Enter Some text: <input type="text" ng-model="name"></label><br>
  Hello <span ng-bind="name"></span>!
</div>

<script>
  angular.module('myapp', [])
    .controller('myController', ['$scope', function($scope) {
      $scope.name = 'there';
    }]);
</script>

</body>
</html>


Below will be output of the program



Hope this tutorial helps you to understand the below stuff :

1. AngularJS expressions using double braces
2. ng-bind expressions




Reactions:

0 comments :

Post a Comment