js模板字符串嵌套html,在元素内插入一个有角度的js模板字符串

在这种情况下,您不想只“插入HTML”,而是对其进行编译。您可以使用该$compile服务创建DOM节点。

var tpl = $compile( '

{{each}}

' )( scope );

如您所见,$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:这都是假设您的模板来自服务器。如果不是,则您的模板应位于指令中,这可以简化操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值