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.
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.
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.
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) {}]);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With