在这种情况下,您不想只是“插入 HTML”,而是编译它。您可以使用$compile 服务创建 DOM 节点。
var tpl = $compile( '<div><p ng-repeat="each in arr">{{each}}</p></div>' )( scope );
如您所见,$compile 返回一个函数,该函数将作用域对象作为参数,根据该函数评估代码。例如,可以使用element.append() 将生成的内容插入到 DOM 中。
重要提示:但在任何情况下都不会有任何与 DOM 相关的代码属于您的控制器。正确的位置是 always 一个指令。这段代码可以很容易地放入指令中,但我想知道你为什么要以编程方式插入 HTML。
您能否在这里阐明一些问题,以便我提供更具体的答案?
更新
假设您的数据来自服务:
.factory( 'myDataService', function () {
return function () {
// obviously would be $http
return [ "Apple", "Banana", "Orange" ];
};
});
您的模板来自服务
.factory( 'myTplService', function () {
return function () {
// obviously would be $http
return '<div><p ng-repeat="item in items">{{item}}</p></div>';
};
});
然后创建一个简单的指令,读取提供的模板,对其进行编译,并将其添加到显示中:
.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 );
}
});
}
};
});
那么在你看来:
<div ng-controller="MyCtrl">
<button ng-click="showContent()">Show the Content</button>
<div show-data template="{{template}}"></div>
</div>
在控制器中,您只需将其绑定在一起:
.controller( 'MyCtrl', function ( $scope, myDataService, myTplService ) {
$scope.showContent = function () {
$scope.items = myDataService(); // <- should be communicated to directive better
$scope.template = myTplService();
};
});
它们应该一起工作!
PS:这都是假设您的模板来自服务器。如果没有,那么您的模板应该在指令中,这样可以简化事情。