2015-03-31 57 views
0

在我正在開發的一個項目上,我們創建了一些SVG地圖。我們有一個系統,可以從我們的數據庫中獲取有關地圖上特定位置的信息。我正在致力於在單擊相關多邊形時使UI Bootstrap工具提示出現。但是,我發現了兩種不起作用的方式。如何向某些SVG元素追溯添加UI Bootstrap Tooltip?

方式不起作用第一,是簡單地設置了總體元件上的指令,而是設置綁定的元素在指令的link功能,像這樣的系統:

(function() { 
    'use strict'; 

    angular.module('app').directive('locationMap', [directive]); 

    function directive() { 
     return { 
      restrict: 'A', 
      scope: { 
       vm: '=' 
      }, 
      link: function(scope, elem) { 
       var polygons = elem.find('polygon'); 
       angular.forEach(polygons, function(current) { 
        var currentElement = angular.element(current); 
        var id = currentElement.attr('id'); 

        // This function in the VM actually looks up 
        // the given ID, and generates some useful details. 
        // The implementation is unimportant for the question. 
        var formattedText = scope.vm.buildDetails(id); 

        currentElement.attr('tooltip', formattedText); 
        currentElement.attr('tooltip-trigger', 'click'); 
        // You have to have this to get this to work with SVG. 
        currentElement.attr('tooltip-append-to-body', true); 
       }); 
      } 
     } 
    } 
})(); 

雖然此代碼生成有效標記,但單擊SVG多邊形實際上不會執行任何操作。進一步的研究顯示,這是因爲Angular在compile時間創建了活動和內容。

所以,接下來我試圖實現一個編譯功能,而不是...

compile: function(elem, attrs) { 
    // Same contents as the link function above. 
} 

...但是,這並不工作,因爲compile沒有訪問的範圍;您必須等到link才能訪問示波器。

但是,如果我在編譯時不這樣做,我就死在水裏了。

問題:以什麼方式可以在點擊交互的SVG上設置UI Bootstrap工具提示,但使用來自當前範圍的詳細文本?我有一種感覺,我忽略了一些非常簡單的東西。

回答

1

當我有link函數時,我就是那裏的大部分。我需要做的是包括$compile服務,並在我的angular.forEach循環使用它...

(function() { 
    'use strict'; 

    angular.module('app').directive('locationMap', ['$compile', directive]); 

    function directive($compile) { 
     return { 
      restrict: 'A', 
      link: function(scope, elem) { 
       var polygons = elem.find('polygon'); 
       angular.forEach(polygons, function(current) { 
        var currentElement = angular.element(current); 
        var id = currentElement.attr('id'); 

        currentElement.attr('tooltip', '{{ vm.buildDetails(' + id + ') }}'); 
        currentElement.attr('tooltip-trigger', 'click'); 
        currentElement.attr('tooltip-append-to-body', true); 

        $compile(currentElement)(scope); 
       });     
      } 
     } 
    } 
})(); 

我這樣做,我的提示事件順利工作。