Search This Blog

Saturday 20 February 2016

directives in angularjs/ recognize click of a hyperlink in a dynamic text using angular JS

I will demonstrate use of directives using the example of recognizing a hyperlink click from a dynamic text.

About directives
To attach custom behavior to html, directives can be used. angular uses a lot of directives.
ng-model, ng-controller, ng-app are default directives provided by angular.

to learn more about directives read: https://docs.angularjs.org/guide/directive

syntax:
directive.js:
var AppControllers = angular.module('starter.controllers');


AppControllers
.directive('mylinkDir',function(LDPServices,$ionicPopup){
return{
           restrict:'A',//attribute
           scope:'true',
           link:function(scope,element,attrs){
           //your code goes here
           }
}

my-dire.html:
<div class="myClass" ng-repeat="myShorttext in myDetailsArray" mylink-dir>
    <p><a href="http://mycustomurl.com">link</a></p>
</div>

Basically i wanted to find clicks on hyperlinks in the div above. so i have attached a directive my div.
The text inside the div is dynamically coming i will not have control (for understanding purpose wrote a p and a inside the div).

Now, in link function i will find click on each element and filter for anchor clicks.
if(event.target.tagName.toLowerCase() === 'a')
{
   var ce = event.href;//gives me href of anchor and i do different actions based on url
}

i will have above if condition in my link function mylinkDir div. so all clicks will be detected and filters for anchors click.

in this kinds of scenario's directives comes handy.
scope of directive is throughout the app. so it can be used in any controller.
$scope will not be available inside a directive.

we can have directives in 4 levels.
E : Element
A : Attribute
C : Class // css class
M: Comment  //it can also recognize comments in code.

in angular2, ng-controllers are deprecated and use of directives encouraged for all the purposes.

please comment for any queries/suggestions.

1 comment: