james.cookie
james.cookie

Reputation: 455

Remove a directive from module in Angular

We are trying to figure out if there is a way to remove/replace/override a set of directives temporarily whilst in a 'preview' mode.

We have tried removing the module(s) that the directives are contained in, e.g.:

angular.module('myModule', []);

but the directives are still active.

Can anyone help?

Upvotes: 7

Views: 3911

Answers (3)

stollr
stollr

Reputation: 7233

In this answer it is described how to remove an angular built-in directive. Based on that idea my suggestion is to do this:

angular.module('myModule', [])
  // ... registering some stuff on the module
  .config(['$provide', function ($provide) {
    // Remove the progress directive of 'ui.bootstrap'.
    // Otherwise we cannot use native progress bar.
    $provide.decorator('{DIRECTIVE_NAME}Directive', ['$delegate', function ($delegate) {
      $delegate.pop();
      return $delegate;
    }]);
  }]);

The $delegate.pop() removes the last directive that has been added with the name {DIRECTIVE_NAME}. So this should be the directive defined by yourself.

Upvotes: 1

guzart
guzart

Reputation: 3730

Internally AngularJS creates factories from directives, by adding a suffix to the directive name. So you can disable the directives by replacing the factories with noop factories.

var noopDirective = function() { return function () {}; };
if (previewMode) {
    // Disable ngPaste directive
    angular.module('myModule')
        .factory('ngPasteDirective', noopDirective);
}

Make sure this is the last executed code.

Upvotes: 8

S McCrohan
S McCrohan

Reputation: 6693

As an alternative, consider putting a preview mode into each of the directives. Pass in an attribute to indicate whether the current state is preview or 'live', and conditionalize the directive template with ng-switch.

Tastes vary, but that feels like a more legible approach to me than redefining the directives on-the-fly.

Upvotes: 1

Related Questions