Search code examples
javascriptangularjsjsplumbngrouteng-view

jsPlumb is not redrawn after view change in angular.js?


I made a two pages using angularjs ngRoute. On first page I show two connected jsPlumb objects. Second page does not contain an Plumb object. However, when I go from first page to second Plumb objects does not disappear. Do you know how to achieve proper jsPlumb refresh with ng-view update?

http://plnkr.co/edit/8592E9BnuwVXuKAJ5Pdx?p=preview

script.js

var app;
app = angular.module('ironcoderApp', [
    'ngRoute',
    'appControllers'
]);

app.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/page1', {
        templateUrl: 'page1.html',
        controller: 'Page1Controller'
      }).
      when('/page2', {
        templateUrl: 'page2.html',
        controller: 'Page1Controller'
      }).
      otherwise({
        redirectTo: '/page1'
      });
  }]);

var appControllers = angular.module('appControllers', []);

app.controller('Page1Controller', ['$scope', '$rootScope', '$routeParams', '$location', '$timeout',

function($scope, $rootScope, $routeParams, $location, $timeout) {
  $scope.text = 'page1';

  $timeout(function(){
    jsPlumb.connect({'source': $("#page1el1"), 'target': $("#page1el2"), 'label': 'te'});
  }, 0);
}
]);

app.controller('Page2Controller', ['$scope', '$rootScope', '$routeParams', '$location',

function($scope, $rootScope, $routeParams, $location) {
  $scope.text = 'page2';
}
]);

app.controller('MainController', ['$scope', '$rootScope', '$location',
function($scope, $rootScope, $location) {
  $scope.text = 'main';
}
]);

page.html:

    <script type="text/ng-template" id="page1.html">

        <div id="page1el1" style="border: 1px red solid; width: 60px;">page1el1</div>
        <br>
        <div id="page1el2" style="border: 1px red solid; width: 60px;">page1el2</div>
        <br>
        page1

        <a href="#/page2">go to page2</a>

    </script>

    <script type="text/ng-template" id="page2.html">

        <br><br><br><br><br><br><br>
        <div id="page2el1" style="border: 1px green solid; width: 60px;">page2el1</div>
        <br>
        <div id="page2el2" style="border: 1px green solid; width: 60px;">page2el2</div>
        <br>

        page2

        <a href="#/page1">go to page1</a>
    </script>


    <div ng-view >

    </div>

Solution

    1. There is a typo in your code.
      When the route is /page2, the controller should be Page2Controller not Page1Controller
    2. We have to manually disconnect the jsPlumb on navigating to page2.

    function($scope, $rootScope, $routeParams, $location, $timeout) {

    $scope.$on('$destroy', function () {
        jsPlumb.detachAllConnections( $("#page1el2"))
    });
    
    $timeout(function(){
        jsPlumb.connect({'source': $("#page1el1"), 'target': $("#page1el2"), 'label': 'te'});
    }, 0);
    });
    

    Here is the updated plunker: http://plnkr.co/edit/mtjamVFRpjphpYE0Yqub?p=preview