Converting an object to a string using AngularJS within a directive

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}}:&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>

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.

Answer №1

The issue lies within the typeOf function in your template. The compiled template is unable to locate this function, resulting in it never being equal to 'object'. To address this, add a controller to your directive to define it.

To resolve this, I made modifications to the plunkr by including the following:

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

After implementing this change, the template now recognizes it as an object. You can view the updated plunkr here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Locate the user, repository, and file path within a GitHub URL

How can I extract the user, repo, and path from a Github URL pasted into a form in order to make API requests? For example, https://github.com/HubSpot/BuckyClient/blob/master/README.md I have started working on a regex solution to locate the different par ...

Encountering error while attempting POST request in POSTMAN - "Unable to modify in restricted editor."

I'm facing a bit of a dilemma here. I can't seem to figure out how to make my editor in Postman stop being read-only. Can anyone lend a hand? Whenever I try to send a Post Request, my editor just won't cooperate and stays in Read-Only mode. ...

Javascript malfunctions upon refreshing the div

After updating data with an ajax function and refreshing the div, I encountered an issue where the jQuery elements inside the div break. How can this be resolved? function getURLParameter(name) { return decodeURIComponent((new RegExp('[?|&]&apo ...

Build a brand new root component in Vue JS

I am facing a challenge with destroying and re-creating the root application component. Below is my template structure: <div id="app"> {{ num }} </div> Here is the code I have implemented: if (app) { app.$destroy(); } else { ...

In Angular 5, a variable's value becomes undefined once it is subscribed to outside of its assigned

I keep encountering an undefined value when trying to assign the subscribed value to a variable in my code snippet below. service.ts getIpAddress() : Observable<any> { return this.http .get(this.Geo_Api) .map((response: ...

How can I access and modify objects within a state array in reactJS when using the setState() method?

Upon reviewing my code, I came across the following declaration: constructor(props) { super(props); this.state = { productArray: [{ barcode: '', name: '' }], numberOfRecords: ...

Searching for li elements that contain text values - a guide

I have a list of letters and I want to filter out any values that contain the text entered by the user in a textbox. Here is the design: Search List: <input type="text" id="txtSearch" /> <ul> <li>Coffee1</li> <li>Coffe ...

Combining Multiple 3D JSON Objects in JavaScript [or jQuery]

Looking to combine multiple JSON objects into one? I have a code snippet that you can use! Here is the code: http://jsfiddle.net/5Uz27/ The issue with this code is that it only merges objects on the first level, causing deeper levels to be overwritten. T ...

My Angular ng-repeat isn't reflecting changes made by a custom filter

My ng-repeat is filtering out items based on a category selected by the user, but when the page loads with the default 'all' category, none of the items are filtered. There are three categories available and the selected category is passed into a ...

Unique rephrased text: "Varied wrapping styles in both

Feeling frustrated with a seemingly commonplace issue. Despite the thousands of times it has been asked before, I can't seem to find an answer on Google. I wanted to neatly display my text within one of my cards, but so far I've only achieved th ...

Running a cfquery in a cfc and passing parameters through AJAX

I am currently setting up a system to retrieve data from my ColdFusion database using JavaScript. However, I am encountering an error and unsure of its cause since I am relatively new to CF. The specific engine I am utilizing is ColdFusion MX 7. Below is ...

IE11/Edge exhibits slow performance with components that have large datasets exclusively

Take a moment to analyze the following code snippet: <GridBody Rows={rows} />. Let's say that in this scenario, rows.length could reach 2000 or more, with each array containing approximately 8 columns. I have encountered a performance bottleneck ...

Issue with ng-hide logic malfunctioning

I am currently developing an Ionic application and encountering some issues with the ng-hide directive. My goal is to display or hide a button based on whether the user has completed registration. The button in question: <button class="button button-c ...

Retrieve the values of private variables within a defined function

While experimenting with typescript, I have encountered an issue that I can't seem to resolve. My project involves using Angular, so I will present my problem within that context. Here is a snippet of my code: class PersonCtrl{ private $scope: I ...

The text-center alignment in Bootstrap doesn't seem to be applying to buttons

After spending a considerable amount of time trying to center two buttons in Bootstrap, I came across the "text-center" class offered by Bootstrap. However, no matter where I include this class, it doesn't seem to have any effect on the alignment of t ...

Update the URL and parse the data in a Backbone collection

For the purpose of development, I am looking to replace the collection with fake JSON results either from a JSON variable or a JSON file. However, I encountered an error when attempting to do so using url http://jsfiddle.net/qhoc/uZhM8/ GET http://fiddle ...

Can users arrange a lineup of choices?

As a beginner, I have a task that seems pretty simple to others but not so much for me. I need to create a feature where a client can order 10 different services in the order they prefer. The idea is to use a dropdown menu or checkboxes to allow the user ...

The directive in an Angular app is not loaded due to lazy loading

Seeking assistance with lazy loading a directive in my Angular application, I am using ui.router and oc.lazyLoad. Below is the code snippet: menu : <ul> <li><a ui-sref="home">Home</a></li> <li><a ui-sre ...

Adjust the size of the sliding tool with images of varying dimensions

My mobile-first slider features three different types of images: tall, horizontally long, and square. I want the size of the slider to be determined by the horizontally long image and then scale and center the other images to fit its size. To achieve this, ...

The callback function is triggered prior to the completion of the request.on function

A custom npm module was developed for downloading files and displaying progress bars using the request and progress libraries. https://github.com/MaxySpark/maxyspark-download However, during testing, the callback function is executing prematurely instead ...