Question

I want to put a directive on an element only if it's not viewed from mobile. As it's an externally maintained plugin I don't want to modify the directive itself. What's the easiest way of doing this?

Was it helpful?

Solution

Create a directive that performs the detection (or receives it), adds the directive if not viewed from mobile, removes itself from the element and then compiles the element.

HTML:

<div not-on-mobile="external-directive">Hello.</div>

JS:

app.directive('notOnMobile', function($compile) {

  // Perform detection.
  // This code will only run once for the entire application (if directive is present at least once).
  // Can be moved into the compile function if detection result needs to be passed as attribute.
  var onMobile = false;

  return {
    compile: function compile(tElement, tAttrs) {

      if (!onMobile) tElement.attr(tAttrs.notOnMobile, '');

      tElement.removeAttr('not-on-mobile');

      return function postLink(scope, element) {

        $compile(element)(scope);
      };
    }
  };
});

Demo: http://plnkr.co/edit/nJntmfiLZ20JCdSWiRDQ?p=preview

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top