AngularJS Directives are used to change or control the behavior of HTML elements. We can modify inner text, 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. Few 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:
This directive indicates root HTML element to AngularJS. It automatically initializes the application when the page is loaded. Everything regarding to AngularJS in is the scope of this directive. If there are more than one ng-app directive, then first one is considered and its inner content is represented as AngularJS Code.
Note: Module Name is Optional
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.
class = “ng-bind: smText”
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. Lets see the example below:
Three points are very important in the above example which are marked using arrows.
- There must be reference to
- 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.
This directive is used in case we want to bind more than one expressions to a HTML element. We provide template expression and evaluated value is displayed on web page as element’s inner text.
To be Continued…