Implementation of Tree Structure View instance code in Angular, angular tree

Source: Internet
Author: User

Implementation of Tree Structure View instance code in Angular, angular tree

In the past two years, Angular has been used to develop many projects, including the display of some tree structure views. Recently, a large number of components have been encapsulated in the project, and some components have also been displayed in a tree structure, so write it out and summarize it.

As we all know, the most typical example of a tree structure is the directory structure. A directory can contain many subdirectories, and a subdirectory can contain several descendant directories, let's take the directory structure as an example to illustrate the implementation of the tree structure in Angular.

First, we want to encapsulate a component to display the tree structure of the entire directory. The Code is as follows:

<!DOCTYPE html> 

Just like the code above, we directly declare the folder-tree label and pass the folder data in the controller as a parameter. A complete tree directory structure is expected to be displayed. Next, let's define the module, Controller, and corresponding commands:

angular.module('treeDemo', [])  .controller("TreeController", function($scope) {   $scope.folder = {     name: 'techs',     children: [       {         name: 'server-side',         children: [           {             name: 'Java'           },           {             name: 'Python'           },           {             name: 'Node'           }         ]       },       {         name: 'front-end',         children: [           {             name: 'jQuery'           },           {             name: 'Angular'           },           {             name: 'React'           }         ]       }     ]   }  })  .directive("folderTree", function() {   return {     restrict: "E",     scope: {       currentFolder: '='     },     templateUrl: 'template/tree.html'   };  }); 

Render as a template for view rendering. Here we will refer to the content in the look template:

<p>{{currentFolder.name}}</p> <ul>   <li ng-repeat="subfolder in currentFolder.children">     <folder-tree current-folder="subfolder"></folder-tree>   </li> </ul> 

As you can see, there is a very important part in the template, that is, the ng-repeat command is used to traverse the subset of the current directory, and then the folder-tree component is used again to render the corresponding subdirectory, this method is perfect. Now let's look at the rendering results:

This method of nesting instructions in the template is perfect, but it is a pity that Angular in earlier versions cannot be implemented, and there will be an infinite recursive loop, resulting in page death, this is caused by Angular's parsing mechanism. After testing, Angular 1.5.0 and later versions are normal, but the running fails in Angular 1.4.9 and later versions. If you are using Angular of a lower version in the project and cause a running failure, you can also slightly modify the template and use ng-include to implement the same function:

<p>{{currentFolder.name}}</p> <ul>   <li ng-repeat="subfolder in currentFolder.children"      ng-include="'template/tree.html'"      ng-init="currentFolder = subfolder">   </li> </ul> 

We have removed the folder-treedirective in the template, used the ng-includedirective, and then introduced the tree.html template. Note that ng-include will create an independent scope so that it can be correctly referenced to the currentFolder variable, we need to initialize currentFolder in each ng-include and assign it to the current subfolder in ng-repeat. In addition, do not forget to add single quotation marks before and after the template path in the ng-include command.

This is indeed acceptable, but you may feel a bit sorry that you failed to use the best solution to implement this tree structure.

In fact, some people have been talking about this problem for a long time. It is surprising that a guy named Mark wrote a service to solve this problem:

/** An Angular service which helps with creating recursive ctives ves. * @ author Mark Lagendijk * @ license MIT */angular. module ('recursionhelper ', []). factory ('recursionhelper ', [' $ compile ', function ($ compile) {return {/*** Manually compiles the element, fixing the recursion loop. * @ param element * @ param [link] A post-link function, or an object with function (s) registered via pre and post pr Operties. * @ returns An object containing the linking functions. */compile: function (element, link) {// Normalize the link parameter // If the link parameter is of the object type, link: {pre: function (...) {}, post: function (...) {} is not processed. // if the link parameter is of the function type, use it as the post-link function and call if (angular. isFunction (link) {link = {post: link} ;}// Break the recursion loop by removing the contents // get and clear the content of the current element, compile var contents = el later Ement. contents (). remove (); var compiledContents; return {pre: (link & link. pre )? Link. pre: null,/*** Compiles and re-adds the contents * compile and re-add content to the current element */post: function (scope, element) {// Compile the contents if (! CompiledContents) {compiledContents = $ compile (contents);} // Re-add the compiled contents to the element compiledContents (scope, function (clone) {element. append (clone) ;}); // Call the post-linking function, if any if (link & link. post) {link. post. apply (null, arguments) ;}}}};}]);

Now we only need to introduce this module, and then use the RecursionHelper service in directive to call the corresponding element node of its compile manual compilation command:

Angular. module ('treedemo', ['recursionhelper ']). controller ("TreeController", function ($ scope) {$ scope. folder = {name: 'techs', children: [{name: 'server-side', children: [{name: 'java'}, {name: 'python '}, {name: 'node'}]}, {name: 'front-end', children: [{name: 'jquery '}, {name: 'angular '}, {name: 'react '}]}). directive ("folderTree", function (RecursionHelper) {return {restrict: "E", scope: {currentFolder: '='}, templateUrl: 'template/tree.html ', compile: function (element) {// here we use the compile method of RecursionHelper to compile the current element of the instruction. Here, the second parameter specifies a function, it is equivalent to the commonly used link function // Of course, we can also specify an object, which contains pre and post functions, corresponding to pre-link and post-link return RecursionHelper respectively. compile (element, function (scope, iElement, iAttrs, controller, transcludeFn) {// Define your normal link function here. // Alternative: instead of passing a function, // you can also pass an object with // a 'pre'-and 'post'-link function. // some variables can be bound to scope. variable = 'Hello world ';});}};});

In the above Code, we introduce the RecursionHelper module when creating the treeDemo module, and then use the RecursionHelper service when creating the folderTree command, and call the compile method of RecursionHelper In the compile method, you can fix the problem above.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.