I tried to create my own recursive directive using AngularJS, which calls itself to convert an object into a representation using a pretty JSON format. Well, at first I used ng-include, calling the script with the template, with ng-if inside it, checking if the current value was the object, if any, the template call itself.
I always think this is a clumsy way to do this, so I am transforming into a directive, much easier.
More and less ... Because I discovered the world of recursive directives and found a lot of things, and the most interesting. I even read it in the Angular source code on github (I recommend you read: https://github.com/angular/angular.js ), and that was good.
I searched so hard and I thinkg I'm almost looking for an awser who will cherish my heart! Because I learn a lot, and you guys will help me.
See my code at the link below: https://github.com/Daymannovaes/htmljs/blob/master/js/directives/recursiveDataTemplateDirective.js
My directive: recursive-data-template = "data", where the data is an object. This directive will iterate over the key and values โโof this object, and if the value was an object, do it again. The condition is satisfied using ng-if = "isObject (value)".
Well, my first problem was an endless loop. I need to delete the content at compile time and then force compile the content in the postLink phase. My question is: ** Why doesn't manual compilation fall into the same infinite loop problem? **
I am compiling the same content, no conditions (if if (! CompiledContent) has been deleted, the infinite loop still does not occur), the difference is (I think), they only fade out elsewhere, but I could not find anyone on the Internet who interests me!
So thanks! (if the link doesn't work, here is the important code):
compile: function(templateElement, templateAttributes) { var templateDirectiveContent = templateElement.contents().remove(); var compiledContent; return function($scope, linkElement, linkAttributes) { if(!compiledContent) { compiledContent = $compile(templateDirectiveContent); } compiledContent($scope, function(clone) { linkElement.append(clone); }); }; }, }
<ul> <li data-ng-repeat="(key, value) in fields"> <span data-ng-if="!isNumber(key)"> {{key}}: </span> <span data-ng-if="isObject(value)" recursive-data-template="value"></span> <span data-ng-if="!isObject(value)"> {{value}} </span> </li> </ul>