我正在使用AngularJs-UI组件进行Bootstrap.我想将填充的模板插入到popover功能的一个数据元素中.这适用于所有不在ng-repeat内部的元素.如何让ng-repeat元素在插值模板中工作?
我在http://plnkr.co/edit/Cuku7qaUTL1lxRkafKzv有一个吸烟者它不工作,因为我不知道如何在plunker中获得Angular-UI-bootstrap.
some content
我的本地范围具有createHTML()
看起来像这样的功能.
angular.module('myApp', ['ngSanitize']) .controller("myController", function(myService){ $scope.createHTML = function() { var thingy = { blah: "foobar", collection: [ "1", "2", "3" ] }; return myService.html_for(thingy); } });
服务是
angular.module('myApp') .service('myService', function($templateCache, $interpolate, $sanitize, $log) { "use strict"; function html_for(thingy) { var template = $templateCache.get('thingyTemplate.html'), link = $interpolate(template), html = link(thingy), unsafe = $sanitize(html); return unsafe; } return { html_for: html_for } });
模板:
KayakDave.. 11
$interpolate
不处理指令ngRepeat
(
解析,插值和编译之间的差异). $interpolate
:
将带有标记的字符串编译为插值函数.HTML $编译服务使用此服务进行数据绑定.
处理ngRepeat
和你想要的其他指令$compile
.但是$compile
,遗憾的是,对于您的用例,会发生一些变化,因为:
它需要一个范围来编译而不仅仅是像上下文$interpolate
.此外,它需要的范围thingy
.
这意味着我们需要在您的模板中引用您的属性,例如{{thingy.blah}}而不是{{blah}}.
当弹出窗口在dom上时,需要进行编译.
弹出窗口仅在dom打开时.
所以我们不能只更换$interpolate
与$compile
您的服务中.
一种方法是替换data-ng-bind-html
为以下指令,其行为类似于ng-bind-html
具有内置的指令$compile
(显然,您应该只使用您知道的安全的html).
.directive('compile', function($compile) { return function(scope, element, attrs) { scope.$watch( function(scope) { return scope.$eval(attrs.compile); }, function(value) { var result = element.html(value); $compile(element.contents())(scope.$parent.$parent); } ); }; });
像这样使用(compile
替换ng-bind-html
:
一个问题是我们需要thingy
在范围内.有几种方法可以处理 - 但为了演示目的,我已经手动返回到调用popover的范围 - 这是2个范围,因此scope.$parent.$parent
.
使用该编译指示不再$interpolate
或者$sanitize
使您的服务功能可以缩小到只有返回相应的模板:
function html_for() { var template = $templateCache.get('thingyTemplate.html'); return template; }
demo fiddle
$interpolate
不处理指令ngRepeat
(
解析,插值和编译之间的差异). $interpolate
:
将带有标记的字符串编译为插值函数.HTML $编译服务使用此服务进行数据绑定.
处理ngRepeat
和你想要的其他指令$compile
.但是$compile
,遗憾的是,对于您的用例,会发生一些变化,因为:
它需要一个范围来编译而不仅仅是像上下文$interpolate
.此外,它需要的范围thingy
.
这意味着我们需要在您的模板中引用您的属性,例如{{thingy.blah}}而不是{{blah}}.
当弹出窗口在dom上时,需要进行编译.
弹出窗口仅在dom打开时.
所以我们不能只更换$interpolate
与$compile
您的服务中.
一种方法是替换data-ng-bind-html
为以下指令,其行为类似于ng-bind-html
具有内置的指令$compile
(显然,您应该只使用您知道的安全的html).
.directive('compile', function($compile) { return function(scope, element, attrs) { scope.$watch( function(scope) { return scope.$eval(attrs.compile); }, function(value) { var result = element.html(value); $compile(element.contents())(scope.$parent.$parent); } ); }; });
像这样使用(compile
替换ng-bind-html
:
<div class="popover-content" compile="content"></div>
一个问题是我们需要thingy
在范围内.有几种方法可以处理 - 但为了演示目的,我已经手动返回到调用popover的范围 - 这是2个范围,因此scope.$parent.$parent
.
使用该编译指示不再$interpolate
或者$sanitize
使您的服务功能可以缩小到只有返回相应的模板:
function html_for() { var template = $templateCache.get('thingyTemplate.html'); return template; }
demo fiddle