AngularJS directive to non interactive html components

Standard

Using utilities to get work done is always comfortable and good practice for sake of code re usability. Recently I came across a requirement where I had to make my several HTML component non clickable.

You can make input types elements non clickable very easily as disabled attribute works well with input types. But wait! what about other elements? Now a days we have lots of third party UI frameworks as angular-material or bootstrap which provides custom stitched input type like md-checkbox in angular material library.

So it means we can not disable it with our traditional disabled attribute. Here discussing concept can save our life.

Idea is very simple i.e apply a simple css on your element and make it non intractable.

pointer-events: none;

Now lets create a css class and apply it to anything and BOOM! you are good to go.

Lets talk more angular now.

Shouldn’t we create a custom attribute which can be short hand for us to apply to our victims? Oh! Obviously yes.

Lets do then.

first create a css class.

.disable {
  pointer-events: none;
}

Now lets create deamon now

(function() {
  angular.module("net.sgoyal.directives.sgDisable",[])
    .directive('sgDisable', function() {
      return {
        priority: 1,
        restrict: 'A',
        link: function(scope, element, attr, ngModel) {
          angular.element(element[0]).addClass('disabled');
        }
      };
    });
})();

Looks simple and straight forward.

Lets look at the implementation.

<div>
    <input type="text" value="editable" /></div>
<div>
    <input type="text" value="disabled" sg-disable/></div>
<div>
    <button>Clickable</button></div>
<div>
    <button sg-disable>Disabled</button></div>

Running plunker can be seen here http://l.sgoyal.net/1YnwId2

Keep me posted with such utilities.

 

Happy Learning

sgoyal

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s