Link opens in new tab

Thanks for your support -- It does make a difference

Hello again and welcome to another Angular.JS video. This time I talk briefly about templates in AngularJS and the ng-include directives, and how to combine them to create recursive templates that can be used to model any number of tree levels.

Here’s the video. Check the code snippets belows:

The Code

In this demo, I used a dummy controller just to have a model to work on, the controller looks like that:

<code>function SampleController($scope) { $scope.sourceItems = [ { text: "Item A", children: [ { text: "Item A-1", children: [ { text: "Item A-1-1" }, { text: "Item A-1-2" } ] }, { text: "Item A-2" }, { text: "Item A-3" }, ] }, { text: "Item B", children: [ { text: "Item B-1" }, { text: "Item B-2" }, { text: "Item B-3", children: [ { text: "Item B-3-1" }, { text: "Item B-3-2" }, ] } ] } ]; } </code>

The obvious magic comes from the HTML, here’s the relevant part:

<code><body ng-app ng-controller="SampleController"> <script type="text/ng-template" id="treeLevel.html"> <ul> <li ng-repeat="item in items"> <input type="checkbox" name="itemSelection" ng-model="item._Selected" /> {{item.text}} <div ng-include=" 'treeLevel.html'" onload="items = item.children"> </div> </li> </ul> </script> <div ng-include=" 'treeLevel.html' " onload="items = sourceItems"> </div> <pre> {{sourceItems | json}} </pre> </body> </code>

You can see the result below:

AngularJS Tree Demo

I hoped you liked this one, and until next video.

Share With Friends:

How did I learn that?

As a bonus for coming here, I'm giving away a free newsletter for web developers that you can sign up for from here.

It's not an anything-and-everything link list. It's thoughtfully collected picks of articles and tools, that focus on Angular 2+, ASP.NET (4.x/MVC5 and Core), and other fullstack developer goodies.

Take it for a test ride, and you may unsubscribe any time.

You might also want to support me by checking these out [Thanks]:

Links open in new tabs

Thanks for your support -- It does make a difference