Sunday, 1 March 2015

AngularJS: ng-include vs directive

It all depends on what you want from your code fragment. Personally, if the code doesn't have any logic, or doesn't even need a controller, then I go with ng-Include. I typically put large more "static" html fragments that I don't want cluttering up the view here.
If there is logic and a lot going on, then directives are the smarter choice (yet more daunting when you're new to AngularJS).

Ng-Include/data-ng-include

Sometimes you will see ng-include's that are affected by their exterior $scope / interface. Such as a large/complicated repeater let’s say. These 2 interfaces are tied together because of this. If something in the main $scope changes, you must alter / change your logic within your included partial.

Directives

On the other hand, directives can have explicit scopes / controllers / etc. So if you're thinking of a scenario where you'd have to reuse something multiple times, you can see how having its own scope connected would make life easier & less confusing.
Also, anytime you are going to be interacting with the DOM at all, you should use a directive. This makes it better for testing, and decouples these actions away from a controller / service / etc, which is something you want!
Tip: Make sure not to use restrict: 'E' if you care about IE8! There are ways around this, but they are annoying. Just make life easier and stick with attribute/etc. <div my-directive />

In conclusion:

·        You should be creating Directives a majority of the time.
·        More extensible
·        You can template and have your file externally (like ng-include)
·        You can choose to use the parent scope, or its own isolate scope within the directive.

·        Better re-use throughout your application