How to add angularjs ui bootstrap tooltips dynamically to existing markup?

前端 未结 2 378
一生所求
一生所求 2021-01-31 11:39

Relatively new to angularjs. Help me understand what\'s going on here!

What I\'m ultimately trying to accomplish: Given a block of text in my html (say in a paragraph e

2条回答
  •  离开以前
    2021-01-31 12:37

    The proper way to handle HTML would be angular directive, lets make a directive (say dynamic-tooltip) that takes two parameter

    • tool-tip message
    • your search word

    In HTML

      

    Hello World check out my foo bar app

    The searchElement will be bind with any model like

      
      
    

    Here when you click search button, the value you typed in search box will be set in searchElement

    The directive definition is:

    app.directive('dynamicTooltip', function($compile) {
        return {
          restrict: 'A',
          scope: {
            tooltipElement: '=',
            dynamicTooltip: '@'
          },
          link: function(scope, element, attrs) {
            var template = '{{tooltipElement}}';
            scope.$watch('tooltipElement', function(value) {
              var previousTooltip = element.find('a');
              angular.forEach(previousTooltip, function(item, i) {
                var el = angular.element(item);
                el.replaceWith(el.text());
              });
              var searchText = scope.tooltipElement;
              if (searchText) {
                replaced = element.html().replace(new RegExp(searchText, "g"), template);
                element.html(replaced);
              }
              $compile(element.contents())(scope);
            });
          }
        }
      })
    

    The directive $watch tooltip-element, so when you change the value, first it try to remove previous tooltips then it try to match your search-word if found any then create the tooltip.

    Check the Demo

提交回复
热议问题