Nov 28, 2015

How To Use AngularJS Expression And Variables

In AngularJS, Expressions Use To Bind Data Just Like "ng-bind". Its Simply Written Inside The Double Braces. These Expressions Are Same As JavaScript Expressions. You Can Use Variables, Operators And Literals.

Lets Write Simple Expression To Output The Value Of "4 + 5".

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<html>
<head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
</head>
<body>
    <p>
        4 + 5 = {{ 4 + 5 }}
    </p>
</body>
</html>

If You See This In Browser You Will Get The Following Output.

4 + 5 = 9

Lets See How We Can Use Variables In Expressions. In Order To Do That Lets Use "ng-init" To Initialize Few Variables. Normally You Don't Need To Do This. Because You Will Get Variables And Objects Through Controllers. These Variables Are Just Like JavaScript Variables. Now Lets See How We Can Create Variables. 

This Is How We Create Numbers In AngularJS.


1
ng-init="Quantity=2;Price=100"

And This Is How We Create Strings In AngularJS.


1
ng-init="firstName='Nifal';lastName='Nizar'"

So Lets Use These In Our Expressions.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<html>
<head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
</head>
<body ng-app="">
    <div ng-init="FirstName='Nifal';LastName='Nizar';Quantity=2;Price=100">
        <span>Customer Name: {{ FirstName+ " " + LastName}}</span>
        <br />
        <span>Invoice Total: {{ Quantity * Price}}</span>
    </div>
</body>
</html>

If you view this in a browser you will get the below output.

Customer Name: Nifal Nizar 
Invoice Total: 200

Hope You Had Good Knowledge About AngularJS Expressions And Variables.

Check My Next Article About AngularJS Repeat And Filters.


No comments:

JWT Token Decode Using Jquery

When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share...