Dynamic includes with Angular.js
Published on Sep 19, 2012In a previous post I show how to use includes to partition views.
In that example, I was using static includes that provide limited flexibility.
What if you want to display different information on the same area of the template based on some condition?
You could use a conditional statement inside the include and render different code accordingly, but doing that will most likely result in bloated and difficult to maintain views.
One solution.
You can use expression evaluation to decide what include to show. In other words, you will be making the decision sooner and keeping your includes small and focused.
The following code declare a function in the controller that return the name of a partial. You can easily make different decisions in here.
function AppCtrl ($scope) {
$scope.getPartial = function () {
return 'partials/issues.html';
}
}
In the view you use the expression as the source for the include instead of a string.
<div data-ng-include data-ng-src="getPartial()"></div>
This approach works OK but make the controller responsible on deciding what view to show, what is not a very good thing.
Conventions
Another approach is to use some convention to name your includes. Let’s say that based in the status of a model you decide what include to show.
You could name you includes in a way that the status is part of the name.
This approach can be used to decide between multiple views easily.
function IssueCtrl ($scope) {
$scope.issue = {
status: 'open'
};
}
<div data-ng-include data-ng-src="'partials/' + issue.status + '.html'"></div>
In the code above angular will look for a partial named open.html in the partials folder.
You can also link the includes to a model property, like shown in the API reference