angular.js 中的视图更改后 jsPlumb 不会重绘?

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

我使用 angularjs ngRoute 制作了两个页面。在第一页上,我展示了两个连接的 jsPlumb 对象。 第二页不包含 Plumb 对象。但是,当我从第一页转到第二页时,Plumb 对象并没有消失。您知道如何通过 ng-view 更新实现正确的 jsPlumb 刷新吗?

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>
  1. 您的代码中有错字。
    当路由为 /page2 时,控制器应为 Page2Controller 而不是 Page1Controller
  2. 我们必须在导航到第 2 页时手动断开 jsPlumb。

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

$scope.$on('$destroy', function () {
    jsPlumb.detachAllConnections( $("#page1el2"))
});

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

这是更新的插件:http://plnkr.co/edit/mtjamVFRpjphpYE0Yqub?p=preview

我发现 jsPlumb.ready() 函数在与 ngView 中的 angular 代码一起使用时不起作用。 对我有用的是将所有准备好的事件代码放在 angular $viewContentLoaded

 $scope.$on('$viewContentLoaded', function (event) { 

    // All the ready code goes here.
}