带有 ng-include 和 onload 的递归模板不呈现任何内容

Recursive template with ng-include and onload not rendering anything

我正在尝试在 AngularJS 中创建一个递归模板。我已经阅读了很多关于它的博客文章和 SO 文章,但无法让我的代码正常工作。

我正在尝试制作一个递归模板来呈现带有变量和运算符的简单嵌套表达式。在这种情况下,数据树中的节点可以是多种类型之一,并且每种类型的呈现方式都不同。我尝试用一​​个 Angular 模板、ng-switchng-include.

来解决这个问题

模板:

<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"> &quot;{{ expression.value }}&quot;</span>
    </ng-switch>
</script>

<ng-include src="'expression.tpl'" onload="expression=testExpression"></ng-include>

数据:

$scope.testExpression = {
    type: "two-sided-operator",
    left: {
        type: "variable",
        name: "foo"
    },
    operator: "==",
    right: {
        type: "literal",
        value: "bar"
    }
};

然而,这不会呈现任何内容。如果我删除内部 ng-includes,它至少会呈现 expression.operator

谁能告诉我我做错了什么? ng-init 语句中对 expression 的赋值是否存在问题?

感谢阅读到这里!

终于通过 ng-repeat 的 hack 实现了这一点。工作模板:

<script type="text/ng-template" id="expression.tpl">
    <ng-switch on="expression.type">
        <span ng-switch-when="two-sided-operator">
            <span ng-repeat="expression in [expression.left]" ng-include="'expression.tpl'"></span>
            {{ expression.operator }}
            <span ng-repeat="expression in [expression.right]" ng-include="'expression.tpl'"></span>
        </span>
        <span ng-switch-when="variable"> {{ expression.name }} </span>
        <span ng-switch-when="literal"> &quot;{{ expression.value }}&quot;</span>
    </ng-switch>
</script>

我对 ng-include 的理解不够深入,无法解释为什么它不起作用 :)