Search code examples
javascriptangularjsvis.jsvis.js-timeline

visjs timeline disappears after angular route reload


I have wrapped a visjs timeline into an angular directive. When I call $route.reload() in the outer controller the timeline disappears. After the page reload completes, the directive still has a reference to the original timeline object and the dom element does not appear to change.

Does anyone know what could cause it to just disappear?

I have created a plunkr but I don't know how to reload the route inside a plunker since that would change the url.

http://plnkr.co/edit/hwShQ2iYR7TOcILSBcEY?p=preview

function timelineViewer() {

  var timeline;
  return {
    restrict: 'E',
    replace: true,
    scope: {
      data: '='
    },
    controller: function($scope) {
      var items = new vis.DataSet();
      var container = document.getElementById('vis-timeline');

      var options = {
        height: 100,
        width: 600,
        zoomMin: 1000 * 60 * 2,
        zoomMax: 1000 * 60 * 20
      };

      items.clear();
      items.add($scope.data);

      timeline = new vis.Timeline(container, items, options);

      console.log('Reloading directive ...')
    },
    template: '<div id="vis-timeline"></div>'
  };
}

Solution

  • To reload the route is needed to setup a route for the controller, see this fork of your plunker. It seems work well with your implemented directive, then I'm not sure about the cause, later I add some changes expecting to fix the problem

    Explaining the plunker:

    controller: function($scope, $element) {
      var items = new vis.DataSet();
      var container = $element[0];
    

    The angular's directive already has a reference to the DOM element of itself ($element), so it can be safely used instead of getting it through document.getElementById

    $scope.$on('$destroy', function () {
      console.log('Destroying directive ...')
      timeline.destroy();
    });
    

    This lines ensure to destroy the timeline when the directive is destroyed, the timeline has the method destroy() to clean the affected DOM elements