简体   繁体   中英

How to inject / load Angular directive in an app

My main.js is in the root folder of app.

-app
 |_ routes.js
 |_ main.js
-components
 |_directives
   |_abc-directive.js

How do I define a directive that can be added from another folder.

I tried this:

abc-directive.js :

var abcDirective = function() {
    // directive code
}

main.js :

app.main = angular.module('main', ['ngRoute', 'components.directives']);
app.main.directive('abcDirective', "<I don't want to define a directive here, 
                                      rather load from diff. folder>");

You can define your controllers, directives in their own modules and add those modules as a dependency to you main module

abc-directive.js

var app = angular.module('directives.abcDirective', [])

app.directive('abcDirective', ...

main.js

var app = angular.module('mainApp', ['directives.abcDirective'])

You can use RequireJS to manage dependencies..

Given that you load the main.js , which include the main module declaration, before the directive file.

You could register the directive in the directive file itself like this:

angular.module('main').directive('abcDirective', abcDirective);

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM