I'm trying to create a recursive template in AngularJS. I've read quite some blog posts and SO posts about it, but cannot get my code to work.
I'm trying to make a recursive template to render simple nested expressions with variables and operators. In this case, the nodes in the data tree can be one of multiple types and each type is rendered differently. I try to address this with one Angular template, ng-switch
and ng-include
.
The template:
<script type="text/ng-template" id="expression.tpl">
<ng-switch on="expression.type">
<span ng-switch-when="two-sided-operator">
<ng-include src="'expression.tpl'" ng-init="expression = expression.left"></ng-include>
{{ expression.operator }}
<ng-include src="'expression.tpl'" ng-init="expression = expression.right"></ng-include>
</span>
<span ng-switch-when="variable"> {{ expression.name }} </span>
<span ng-switch-when="literal"> "{{ expression.value }}"</span>
</ng-switch>
</script>
<ng-include src="'expression.tpl'" onload="expression=testExpression"></ng-include>
The data:
$scope.testExpression = {
type: "two-sided-operator",
left: {
type: "variable",
name: "foo"
},
operator: "==",
right: {
type: "literal",
value: "bar"
}
};
This however does not render anything. If I remove the internal ng-include
s, it does render at least expression.operator
.
Can anyone tell me what I am doing wrong? Could there be an issue with the assignment to expression
in the ng-init
statement?
Thanks for reading this far!