Angular如何正确销毁指令

时间:2015-08-06 18:53:23

标签: angularjs angularjs-directive

我有一个'regionMap'指令,其中包含渲染和销毁地图的方法。地图在模态内部渲染,单击模态关闭按钮时,将调用“regionMap”destroy方法,该方法应从页面中删除元素和范围。但是,当返回到包含“region-map”元素的模态页面时,不会删除先前的“region-map”元素,从而导致显示多个地图。关闭模态时从页面中删除regionMap指令的正确方法是什么?

//指令

(function(){
'use strict';

angular.module('homeModule')
.directive('regionMap', regionMap);

function regionMap() {

    var directive = { 
            restrict: 'E',
        template: '',
        replace: true,
        link: link,
        scope: {
            regionItem: '=',
            accessor: '='
        }
    }

    return directive;

    function link(scope, el, attrs, controller) {
        if (scope.accessor) {
            scope.accessor.renderMap = function(selectedRegion) {
                var paper = Raphael(el[0], 665, 245);
                paper.setViewBox(0, 0, 1100, 350, false);
                paper.setStart();
                for (var country in worldmap.shapes) {
                    paper.path(worldmap.shapes[country]).attr({
                      "font-size": 12,
                      "font-weight": "bold",
                      title: worldmap.names[country],
                      stroke: "none",
                      fill: '#EBE9E9',
                      "stroke-opacity": 1
                    }).data({'regionId': country});
                }

                paper.forEach(function(el) {
                    if (el.data('regionId') != selectedRegion.name) {
                      el.stop().attr({fill: '#ebe9e9'});
                    } else {
                      el.stop().attr({fill: '#06767e'});
                    }
                });
            }
            scope.accessor.destroyMap = function() {
                scope.$destroy();
                el.remove();
            }
        }
    }
 }


})();

// controller template:

<region-map accessor="modalvm.accessor" region-item="modalvm.sregion"></region-map>

// controller:

vm.accessor = {};

...

function showMap() {

$rootScope.$on('$includeContentLoaded', function(event) {
    if (vm.accessor.renderMap) {
        vm.accessor.renderMap(vm.sregion);
    }
});

function closeMap() {
    if (vm.accessor.destroyMap) {
        vm.accessor.destroyMap();
    }
    $modalInstance.dismiss('cancel');
}

1 个答案:

答案 0 :(得分:0)

该问题与加载带有指令的模板有关。通过添加一个var来检查地图是否先前已经渲染来修复它:

vm.accessor.mapRendered = false;
$rootScope.$on('$includeContentLoaded', function(event) {
  if (vm.accessor.renderMap && !vm.accessor.mapRendered) {
    vm.accessor.renderMap(vm.selectedRegions);
    vm.accessor.mapRendered = true;
  }
});