Horen
Horen

Reputation: 11382

AngularJS: ng-include or directive

I have a top menu in my angular app. Since the menu is static, it is not included in the ng-view. I could leave the menu source in the index.html, but for cleaner markup I decided to pull it into a partial.

Now my question: Is it better practice to use ng-include and a separate controller or implement a custom directive instead?

I won't really reuse the code so I think ng-include would be fine but a directive somehow feels more "the angular way"...

Upvotes: 0

Views: 184

Answers (3)

rchawdry
rchawdry

Reputation: 1266

I would seriously suggest looking at ui-router (https://github.com/angular-ui/ui-router), which gives you an enormous amount of flexibility to setup layout pages that have different sections (main, left-nav, content). It's a much more flexible means of using Angular to setup page structure so that you don't have to repeat yourself. It's also tremendously powerful by allow you precise control over different section of a page depending on where people are in your application.

The docs do a reasonably good job explaining it, but try to focus on the area which talks about multiple-named views.

ng-include will work fine, but it if you want more control, ui-router is the way to go.

Upvotes: 1

JeffryHouser
JeffryHouser

Reputation: 39408

Is it better practice to use ng-include and a separate controller or implement a custom directive instead?

Best practice is always subjective.

I have taken this approach:

  1. If I want to build for reuse; I create a directive.
  2. If I want to separate code for organizational purposes, I use an ng-include

Upvotes: 1

Amir Popovich
Amir Popovich

Reputation: 29846

ng-include is just fine to load partial views for your application(I assume that your index.html is kind of a master page with one ng-view section).

Each section that is loaded can have it's own controller(e.g. if you have a div with 'hot news' that fetches stuff from the db, you can just include the partial view using ng-include and let the new view have a ng-controller directive that will perform a ajax call to fetch stuff from the db).

I would add a directive only if need extra functionallity.
If you can live without it then why bother?

Upvotes: 1

Related Questions