使用uib-popover-html的ui.bootstrap- directrive不起作用

Kos*_*aft 3 angularjs angularjs-directive angular-ui-bootstrap

我试图用popover创建一个指令.

我想为此使用ui.bootstrap.不幸的是它没有任何显示.这是一个带有例子的plunker.

<div>
  Popover uib (notworking- uib-popover-html)  ->
  <div mydirectiveuib ng-model="name"></div>
</div>

app.directive('mydirectiveuib', function(){
    return{
        restrict: 'EA',
        replace: true,
        scope: {
            ngModel: '='
        },
        template: ' <span class="test">aaa<img  popover-trigger="mouseenter" popover-placement="right" uib-popover-html="<h2>{{ngModel}}</h2>" width="20" height="20" src="http://icons.iconarchive.com/icons/dakirby309/windows-8-metro/48/Folders-OS-Info-Metro-icon.png" alt="info icon" /></span>',
        link: function(scope, iElement, iAttrs) {
        }
  };
})
Run Code Online (Sandbox Code Playgroud)

如果我将uib-popover-html更改为仅popover它正在工作.

<div>
   Popover (working) -> 
   <div mydirective ng-model="name"></div>
</div>

app.directive('mydirective', function(){
        return{
            restrict: 'EA',
            replace: true,
            scope: {
                ngModel: '='
            },
            template: ' <span class="test">aaa<img  popover-trigger="mouseenter" popover-placement="right" popover="<h2>{{ngModel}}</h2>" width="20" height="20" src="http://icons.iconarchive.com/icons/dakirby309/windows-8-metro/48/Folders-OS-Info-Metro-icon.png" alt="info icon" /></span>',
            link: function(scope, iElement, iAttrs) {
            }
      };
    })
Run Code Online (Sandbox Code Playgroud)

知道我做错了什么以及如何解决它?

Ste*_*ieP 9

您可能已经找到了解决方案,因此这可能适用于具有类似问题的未来读者(就像我一样).

我们需要仔细查看这里的ui-bootstrap文档,其中说:

popover有两个版本:uib-popover和uib-popover-template:

  • uib-popover 仅接受文本并将转义为弹出框体提供的任何HTML.
  • uib-popover-html采用一个计算结果为html字符串的表达式.用户有责任确保将内容安全放入DOM中!
  • uib-popover-template获取指定用于弹出框体的模板位置的文本.请注意,这需要包装在标签中.

因此,参数uib-popover-html是一个表达式,其值为html字符串,而不是html字符串本身.所以你可以:

...
template: '<ANY ... uib-popover-html="popoverHtml" ... >',
link: function(scope, iElement, iAttrs) {
  scope.popoverHtml = '<div><h2>{{ngModel}}</h2><p>Hello {{ngModel}}</p></div>';
} 
Run Code Online (Sandbox Code Playgroud)

但是,这不能正常工作,因为它可能不安全,并且"用户有责任确保将内容安全放入DOM中".要使其工作,需要了解并实现严格的上下文转义.这是我放弃HTML方法的地方,有利于使用uib-popover-template.

不要问我为什么这样更安全,但您的自定义指令的以下模板有效:

...
template: '<ANY ... uib-popover-template="\'popover.html\'" popover-trigger="mouseenter" ... > Popover </ANY>',
// NB need to escape the single 's    here ^    and here ^
...
Run Code Online (Sandbox Code Playgroud)

注意当uib-popover-template"获取指定模板位置的文本"时,位置需要呈现,"'popover.html'"因此单引号需要在指令的内联模板中转义(或使用外部模板).

其他要纠正的事情:

  • 确保版本angular.js和ui-bootstrap-tpls.js是最新的.
  • 确保ui-bootstrap正确注入应用程序(你有@Kosmno但我没有!)
  • 确保使用的元素启动应用程序 ng-app

这是你的工作人员,以及我制作的另一个人.