AngularJS Directives - Part One

AngularJS Directives are used to change or control the behavior of HTML elements. We can modify inner text, and inner html. This is also used to limit the functionalities of HTML elements.

These are nothing but extended attributes of HTML, prefixed with ng-. We can define our own custom directives as well. A few of the most useful directives are listed below,

  • ng-app - This directive is used to initialize AngularJS application.
  • ng-init - This directive is used to initialize application data.
  • ng-model - This directive is used to bind the value of HTML control to application data.
Let's understand various AngularJS directives with examples,
  1. ng-app

    This directive indicates root HTML element to AngularJS. It automatically initializes the application when the page is loaded. Everything regarding AngularJS in is the scope of this directive. If there are more than one ng-app directives, then the first one is considered and its inner content is represented as AngularJS Code.



    We provide a module name to AngularJS application, which is further used in the JavaScript for handling the application e.g. here module name is 'angularJSApp'.

    Note - Module Name is Optional.

  2. ng-bind

    ng-bind directive changes the content of associated HTML element by the value of expression. If the value of expression changes, content of HTML element is also changed without page refresh.




    This can be used in two ways shown above.

    ng-bind="smText"
    or
    class = "ng-bind: smText"

    Output


  3. ng-bind-html

    ng-bind is used to provide text as inner content whereas if we have requirement and want to provide or modify insecure scripted inner HTML content then ng-bind-html is the best way to use. Using this directive, we can update or add inner HTML of associated HTML element. Let's see the example below:



    Three points are very important in the above example which are marked using arrows.

    • There must be reference to angular-sanitize.js
    • AngularJS directive ng-bind-html will be used to inject inner HTML
    • A parameter 'ngSanitize' must be provided to module API for making this functional.

      Output

  4. ng-bind-template

    This directive is used in case we want to bind more than one expression to anHTML element. We provide template expression, and  the evaluated value is displayed on web page as element's inner text.



    Output


Up Next
    Ebook Download
    View all
    Learn
    View all