Search code examples
javascriptangularjsjstree

Populating jstree threeview from angular variable


So far I've done 90% of what I had to do with my very limited front-end skills so I now need help.

I'm using jstree to build treview and it works fine for static data (the one in else block) as shown below.

<script>
    $(function() {
        $("#list").jstree({
            "core": {
                "data": function (node, cb) {
                    if (node.id === "#") {
                        cb([{
                            "text": "Root",
                            "state": {"opened": true},
                            "children": true
                        }]);
                    } else {
                        // This is the one I am try to populate dynamicaly
                        cb([{"id":"1","text":"Lis 1"},{"id":"2","text":"Lis 2"}]);
                    }
                }
            }
        });
    });
</script>

However, I now need to populate else block with dynamic result-set coming from angular variable vm.list (available to dump with {{ vm.list }} in HTML page) so how can I do it? The documentation has some details about population data dynamically (html, array/json, ajax, lazy load and callback) but nothing like I need.

Passing vm as third param in callback function and changing else block to cb(vm.cat); didn't do the trick. If my front-end knowledge wasn't at the rock bottom, I would have come up with better tries!

My angular controller looks like:

'use strict';

module.exports = ['$on', '$timeout', 'listService',
    function($on, $timeout, listService) {
        var vm = this;
        ....
        load();
        ....

        function load() {
            // This is actually coming from an API and massive
            vm.cat = [{'id':'1', 'text':'Lis 1'}, {'id':'2', 'text':'Lis 2'}];
        };
    }
];

Solution

  • I have a working solution but don't like it so I'll wait for someone with better solution otherwise I'll regrettably accept this as it dumps content into a DOM element and reads its content to create the tree which is a bit hacky and heavy in my opinion.

    <div id="data" style="display: none">{{ vm.cat }}</div>
    
    
    $(function() {
        var data = $('#data').text();
        if (data) {
            $("#list").jstree({
                "core": {
                    "data": JSON.parse(data)
                }
            });
        }
    });