Pergunta

I am using AngularJs in my project, so all the main content in my app is loaded using ng-view directive of angular, I wanted to implement a timeline using TimelineJs in my app, the timeline get's an id (place to put the timeline) but my div with that id is loaded through angular asynchronously so when the TimelineJs scripts run the div#id does not exist, any idea how to solve this?

here is the code:

$(document).ready(function() {
    createStoryJS({
        type:       'timeline',
        width:      '800',
        height:     '400',
        source:     './timeline.json',
        embed_id:   'dash-tim'
    });
});

and here is the Error:

Uncaught TypeError: Cannot call method 'appendChild' of null storyjs-embed.js:45
T storyjs-embed.js:45
createStoryJS storyjs-embed.js:45
(anonymous function) extra.js:21
fire jquery-1.8.2.js:974
self.fireWith jquery-1.8.2.js:1082
jQuery.extend.ready jquery-1.8.2.js:406
DOMContentLoaded
Foi útil?

Solução

Here is how I have implemented it.

I have an angular directive that calls the timelineJS code to modify the dom (I'm not an angularjs expert by a longshot, but that seems to be the pattern others recommend).

HTML

<div ng-app="StoryUniverse" ng-controller="EventsListCtrl">
        <div id="my-timeline" timeline-js></div>
</div>

Angular Directive

app.directive('timelineJs',  function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            postpone = $timeout(function() {
                createStoryJS({
                    type:       'timeline',
                    width:      '800',
                    height:     '600',
                    source:     scope.events,
                    embed_id:   'my-timeline',
                    css:        'lib/timelinejs/css/timeline.css',
                    js:         'lib/timelinejs/js/timeline.js'
                });
            }, 0);
            console.log("Running timelineJS");
        }
    }
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top