Tuesday, 16 January 2024

AngularJS Directives and AngularJS Expressions

 

  • Definition: Code snippets embedded in HTML that AngularJS evaluates and renders.
  • Syntax: Enclosed in double curly braces {{ expression }}.
  • Purpose:
    • Dynamically display data from the model.
    • Perform simple calculations.
    • Modify the HTML content based on conditions.
  • Examples:
    • {{ name }} displays the value of the name variable.
    • {{ 1 + 2 }} evaluates to 3.
    • {{ items.length }} displays the number of items in an array.
  • Program:


  • <!DOCTYPE html>

    <html>
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
                </script>
    <title>AngularJS Expression</title>
    </head>
    <body style="text-align:center">
        <h1 style="color:green">GeeksforGeeks</h1>
        <h3>AngularJS Expressions</h3>
        <div ng-app=""
            ng-init="name='GeeksforGeeks'">  
        <p> {{ name }} is a portal for geeks.</p>
        </div>
    </body>
    </html> 


AngularJS Directives:

  • Definition: Instructions in HTML that tell AngularJS to modify the DOM (Document Object Model).
  • Types:
    • Built-in directives: Provided by AngularJS itself (e.g., ng-modelng-repeatng-if).
    • Custom directives: Created by developers to extend functionality.
  • Purpose:
    • Add behavior to HTML elements.
    • Create reusable components.
    • Implement dynamic features.

Key Points:

  • Expressions are often used within directives to provide dynamic values.
  • Directives can access and manipulate the scope, which contains data and functions.
  • AngularJS expressions have limitations compared to JavaScript expressions:
    • No conditionals (if/else), loops (for/while), or exceptions (try/catch).
    • No function declarations.
    • No bitwise operators or void operator.

Common Directives:

  • ng-app: Defines the root element of an AngularJS application.
  • ng-model: Binds input fields to model properties.
  • ng-bind: Binds expressions to HTML elements.
  • ng-repeat: Iterates over a collection and creates multiple elements.
  • ng-if: Conditionally includes or excludes elements.
  • ng-click: Binds click events to expressions.

Example: 

<div ng-app="" ng-init="firstName='John'">

<p>The name is <span ng-bind="firstName"></span></p>

</div>


AngularJS Example

<div data-ng-app="" data-ng-init="firstName='John'">

<p>The name is 

<span data-ng-bind="firstName"></span>

</p>

</div>


No comments:

Post a Comment

Case Study: Smart City Street Light Control with IoT Smart City Street Light Control with IoT ...

Popular Posts