Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a directive to be used in any module?

How can I create a directive without linking it to a specific module which can be used in any module, such as the build-in directives.

like image 607
Ghyath Serhal Avatar asked Nov 19 '13 12:11

Ghyath Serhal


People also ask

How do you create a directive file?

To create a custom directive we have to replace @Component decorator with @Directive decorator. So, let's get started with creating our first Custom Attribute directive. In this directive, we are going to highlight the selected DOM element by setting an element's background color. Create an app-highlight.

How can we create a custom directive in Angular?

Creating a custom directive is easy. Just create a new class and decorate it with the @Directive decorator. We need to make sure that the directive is declared in the corresponding (app-) module before we can use it. If you are using the angular-cli this should be done automatically.


2 Answers

A directive or service has to belong to a module. What you can do is create separate modules for your directives and then inject them into your main application module. Here's my set up:

window.app = angular.module('app', ['ngRoute', 'app.system', 'app.animations', 'app.cart']);


angular.module('app.system', []);
angular.module('app.animations', []);
angular.module('app.cart', []);

Now your Service can be in its own module and called from within the app module. This is essentially what Ajay said.

angular.module('app.cart').factory("Cart", ['$resource', function($resource) {}]);
like image 174
Pasha Riger Avatar answered Sep 20 '22 07:09

Pasha Riger


Short answer: no, it is not possible. All directives must be part of a module.

The Angular docs say

Much like controllers, directives are registered on modules. To register a directive, you use the module.directive API. module.directive

There isn't a way to define a directive outside of a module.

The Angular built-in directives themseves are defined on a module called ng - see the source code.

This module is created using the Angular internal method setUpModuleLoader (see AngularPublic.js and loader.js).

This function is not part of the Angular public API, so you can't access it yourself. You need to define your directives in your own module. Any app module which depends on this module will be able to use your directives.

It's a very Angular way of looking at things - avoid public objects, but make things injectable wherever possible.

like image 29
joews Avatar answered Sep 19 '22 07:09

joews