栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

在这种情况下,您不希望仅“插入HTML”,而是对其进行编译。您可以使用该

$compile
服务创建DOM节点。

var tpl = $compile( '<div><p ng-repeat="each in arr">{{each}}</p></div>' )( scope );

如您所见,

$compile
返回一个函数,该函数将范围对象作为参数,对代码进行评估。
element.append()
例如,可以使用将结果内容插入DOM

重要说明 :但是在 任何情况下 ,控制器中都不会包含任何与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 '<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:这都是假设您的模板来自服务器。如果不是,则您的模板应位于指令中,这可以简化操作。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/568985.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号