代码改变世界

AngularJS Best Practices: ng-include vs directive

2016-01-04 00:03  zhangpengc  阅读(220)  评论(0编辑  收藏  举报

For building an HTML template with reusable widgets like header, sidebar, footer, etc. Basically the main content is the central DIV which will have its content varying between routes, header and footer will be almost always the same, sidebar can vary in certain pages.

Based on the your page structure, at least for headers and footers you do not need to use directives, there would be only single rendering for these controls. Standard ng-include with a partial and maybe a linked controller would do. Remember ng-include itself is a directive.

Directive would be useful where you want a component that needs to used across pages, your headers and footer nav do not fit this bill as there is a single instance of these elements on the page.

But I prefer directives because ng-include only breaks down the view part into smaller modules. By using directives, even if it is used only once, you still nicely modularize your page into smaller independent components. Markup of the parent page looks much nicer and you don't have to clutter your controller with more methods.