且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AngularJs:抓取编译的 html 并设置为工具提示

更新时间:2022-04-21 09:07:03

你可以这样做:

HTML:

<li ng-repeat="phone in phones">      
       <div phone-info index="{{$index}}">
         <p tooltip-html-unsafe="{{tooltips[$index]  }}">A tooltip should appear on top of this line ({{ phone.name }} - {{ phone.snippet }})</p>         
       <div>
</li>

添加到控制器:

$scope.tooltips = [];

指令:

app.directive('phoneInfo', function($compile, $timeout) {
  /* wrap in root element so we can get final innerHTML*/
  var tipTemplate = '<div><p> This will be the content of {{phone.name}} injected in the tooltip </p><div>';

  return {
    link: function(scope, el, attrs) {
      var tipComp = $compile(tipTemplate)(scope)
      $timeout(function() {
        scope.tooltips[attrs.index] = tipComp.html()

      });
    }
  }
})

使用 index 来避免创建孤立的作用域.也可以使用隔离范围完成并创建 phone 的属性而不是使用 scope.tooltips[index]

Used index to avoid creating an isolated scope. Can also be done with isolated scope and create a property of phone instead of using scope.tooltips[index]

演示