gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:22:39 25 4
gpt4 key购买 nike

我需要一些帮助来让 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com