我知道当我想将HTML插入视图时,我会使用'ng-bind-html'
或'ng-bind-html-unsafe'
。
我不知道的是,如何插入HTML并使Angular解析其内容
即。如果有'ng-repeat'
,我想让Angular解析它吗?
示例:
HTML:
<div ng-repeat="t in ts" ng-bind-html-unsafe="t.html()"></div>
JS:
function Controller($scope) {
$scope.ts = {obj1: new obj(), obj2: new obj(), ob3: new obj()};
}
function obj() {
// which may be "<div ng-repeat="s in somthing">{{s}}</div>"
// or "<ul><li ng-repeat="s in somthing">{{s.k}}</li></ul>"
// or something else
var _html;
this.html = function() {
return _html;
}
}
我尝试使用上述内容,但Angular只是按原样打印{{s}}
或{{s.k}}
。
答案 0 :(得分:44)
您可以使用$compile
服务(docs)将任意HTML编译为角度视图。
app.run(function($rootScope, $compile, $rootElement) {
// We'll create a new scope to use as the context for the view.
$scope = $rootScope.$new();
$scope.model = [{name: 'first'}, {name: 'second'}, {name: 'third'}];
// Calling `$compile(html)` returns a function that, when called with
// a context object, links the compiled HTML to the given context (e.g.
// binds scope-based expressions in the view to the passed in scope).
var html = "<div ng-repeat='m in model'>{{m.name}}</div>";
var linkingFunction = $compile(html);
var elem = linkingFunction($scope);
// You can then use the DOM element like normal.
$rootElement.append(elem);
});
在这种情况下,我将视图附加到$rootElement
(这是在引导模块时使用的元素,通常是ng-app
指令);在很多情况下,你会在指令的链接函数中执行此类操作,并且可以访问相关元素。当然,您可以使用jQuery或jqLite获取原始HTML,但请记住在链接范围之前至少允许一个摘要周期(否则HTML将不会使用范围中的值进行更新)
工作示例:http://jsfiddle.net/BinaryMuse/QHhVR/
向下ng-include
指令的内容,Angular's doing this very thing:
$compile(currentElement.contents())(currentScope);
<强> [更新] 强>
这是一个更完整的示例,演示了更接近您更新的问题的内容:
app.controller("MainController", function($scope) {
$scope.ts = [
{
elements: ['one', 'two', 'three'],
html: '<div ng-repeat="elem in t.elements">{{elem}}</div>'
},
{
things: [8, 9, 10],
add: function(target) {
var last = target[target.length - 1];
target.push(last + 1);
},
html: '<ul><li ng-repeat="num in t.things">{{num}}</li>' +
'<li><button ng-click="t.add(t.things)">More</button></li></ul>'
}
];
});
app.directive("bindCompiledHtml", function($compile, $timeout) {
return {
template: '<div></div>',
scope: {
rawHtml: '=bindCompiledHtml'
},
link: function(scope, elem, attrs) {
scope.$watch('rawHtml', function(value) {
if (!value) return;
// we want to use the scope OUTSIDE of this directive
// (which itself is an isolate scope).
var newElem = $compile(value)(scope.$parent);
elem.contents().remove();
elem.append(newElem);
});
}
};
});
<div ng-controller="MainController">
<div ng-repeat="t in ts" bind-compiled-html="t.html"></div>
</div>
工作示例:http://jsfiddle.net/BinaryMuse/VUYCG/
HTML代码段使用t.elements
和t.things
并不值得,因为t
是由外部的ng-repeat
创建的范围值 HTML。如果你愿意的话,你可以做一些范围体操让这更好一些。
答案 1 :(得分:1)
如果重复中元素的选项有限,则可以使用ng-switch代替ng-include,如果HTML来自服务器,则可以使用ng-include。
答案 2 :(得分:0)
这样的东西?
<div ng-repeat="item in items">
<div ng-bind-html-unsafe="item.html"></div>
</div>
,其中
items = [
{
html: 'test<br/>test'
},
{
html: 'test2<br/>test2'
}
]