Can anyone assist me in ensuring that AngularJS preserves non-string values in directive attributes?
While searching for a method to display a tree structure in HTML from JSON data, I came across this code snippet: http://jsfiddle.net/n8dPm/
I've been attempting to customize it for my project, as demonstrated in the code snippet below.
Below is my controller/directive implementation:
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);
});
};
}
};
});
Here is my template:
<script type="text/ng-template" id="tree_renderer.html">
{{key}}:
<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>
The code seems to be functioning properly, except for one issue. Angular is converting the value of "content" to a string, causing the recursive function to fail as it cannot iterate over a string.
I have come across similar questions, such as this one, but their problem stemmed from using "@" in the directive scope, which converts values to strings. However, I am using "=", which should retain the original type.
Here is the output I am encountering with the test data provided in the code above:
Any assistance on this matter would be greatly appreciated. If additional information is needed, please let me know.