javascript - AngularJS 在指令中将对象转换为字符串

标签 javascript angularjs angularjs-directive angularjs-scope

我需要一些帮助来让 AngularJS 在指令属性中维护我的非字符串值。

我正在寻找一种从一段 JSON 中呈现 HTML 树结构的方法,我找到了这段代码:http://jsfiddle.net/n8dPm/

我一直在努力为我的项目调整它,如下面的代码所示。

我的 Controller /指令显示在这里:

cxpControllers.controller("ProductTocCtrl", ["$scope", "$http", "$routeParams",
function ProductTocController($scope, $http, $routeParams) {
    $scope.typeOf = typeOf;

            //test value
    $scope.contents = {
        "id": 1,
        "name": "Test",
        subsections: [
            {
                id: 2,
                name: "Test1.1",
                link: "test11.xml",
                test: 34
            },
            {
                id: 3,
                name: "Test1.2",
                link: "test12.xml",
                test: 95
            }
        ]
    }

}]);

cxpControllers.directive('tree', function($compile) {
return {
    restrict: 'E',
    scope: {key: "=", content: "="},
    templateUrl: "tree_renderer.html",
    compile: function(tElement, tAttr) {
        var contents = tElement.contents().remove();
        var compiledContents;
        return function(scope, iElement, iAttr) {
            if(!compiledContents) {
                compiledContents = $compile(contents);
            }
            compiledContents(scope, function(clone, scope) {
                iElement.append(clone);
            });
        };
    }
};
});

然后这是我的模板:

<script type="text/ng-template" id="tree_renderer.html">
{{key}}:&nbsp;

<ul ng-if="typeOf(content) == 'object' && content != null">
    <li ng-repeat="(key, content) in content">
        <tree key="key" content="content"></tree>
    </li>
</ul>

<span ng-if="typeOf(content) != 'object'">
    "{{content}}"
</span>

</script>

<ul>
    <li ng-repeat="(key, content) in contents">
        <tree key="key" content="content"></tree>
    </li>
</ul>

除一个问题外,这可行。 Angular 正在将“content”的值转换为字符串,从而阻止递归工作,因为它无法遍历字符串。

我见过其他类似的问题,例如here ,但他们的问题是他们在指令范围内使用了“@”,它会转换为字符串。但由于我使用的是“=”,它应该保持类型。

这是我在上面的代码中显示的测试数据所看到的输出:

如果您能提供任何帮助,我将不胜感激。如果您需要更多信息,我很乐意提供。

最佳答案

问题出在模板中的 typeOf 函数 上。编译后的模板找不到此函数,因此它永远不会等于“对象”。将 Controller 添加到您的指令以定义它。

我采取了 plunkr 并添加了这个:

controller: function($scope) {
    $scope.typeOf = function(val) {
        return typeof val;
    };
},

它确实将它识别为一个对象。查看更新的 plunkr here .

关于javascript - AngularJS 在指令中将对象转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20912188/

相关文章:

javascript - Angular equals 深度比较并返回每个项目的差异

angularjs - 如何调用 AngularJS 指令中定义的方法?

javascript - Angular JS : What is the need of the directive’s link function when we already had directive’s controller with scope?

javascript - 在 AngularJS 指令中调用传入的函数

javascript - 在客户端清理/重写 HTML

javascript - 页面刷新后 ng-click 停止工作

Javascript - getAttribute 不适用于 getElementsByTagName

javascript - 使用 angularJS 服务将 `setInterval` 转换为 AngularJS

javascript - 当用链接标签包裹时,Logo 不会在 React 中显示

javascript - 使用 Javascript 将字典列表转换为列表字典