在这种情况下,您不想只“插入HTML”,而是对其进行编译。您可以使用该$compile服务创建DOM节点。
var tpl = $compile( '
{{each}}
如您所见,$compile返回一个函数,该函数将范围对象作为参数,对代码进行评估。生成的内容可以使用插入到DOM中element.append()。
重要说明:但是在任何情况下,控制器中都不会包含任何与DOM相关的代码。适当的地方始终是指令。可以将这些代码轻松地放入指令中,但是我不知道为什么您要以编程方式完全插入HTML。
您能否在这里阐明一些信息,以便我提供更具体的答案?
更新资料
假设您的数据来自服务:
.factory( 'myDataService', function () {
return function () {
// obviously would be $http
return [ "Apple", "Banana", "Orange" ];
};
});
您的模板来自服务
.factory( 'myTplService', function () {
return function () {
// obviously would be $http
return '
{{item}}
};
});
然后,您创建一个简单的指令,该指令读取提供的模板,对其进行编译,然后将其添加到显示中:
.directive( 'showData', function ( $compile ) {
return {
scope: true,
link: function ( scope, element, attrs ) {
var el;
attrs.$observe( 'template', function ( tpl ) {
if ( angular.isDefined( tpl ) ) {
// compile the provided template against the current scope
el = $compile( tpl )( scope );
// stupid way of emptying the element
element.html("");
// add the template content
element.append( el );
}
});
}
};
});
然后从您的角度来看:
Show the Content
在控制器中,您只需将其捆绑在一起:
.controller( 'MyCtrl', function ( $scope, myDataService, myTplService ) {
$scope.showContent = function () {
$scope.items = myDataService(); //
$scope.template = myTplService();
};
});
它应该一起工作!
PS:这都是假设您的模板来自服务器。如果不是,则您的模板应位于指令中,这可以简化操作。