首页 > 语言 > JavaScript > 正文

AngularJs中 ng-repeat指令中实现含有自定义指令的动态html的方法

2024-05-06 15:02:27
字体:
来源:转载
供稿:网友

今天用angular写table的时候,遇到了一个问题。在ng-repeat中,含有动态的html,而这些html中含有自定义指令。

因为希望实现一个能够复用的table,所以定义了一个指令myStandTable,指令代码大概如下:

var myCommon = angular.module("myCommon",[]);myCommon.directive("myStandTable", function () { return { restrict: "A", templateUrl: "app/template/tableTem.html", transclude: false, replace: true, controller: function ($scope,$compile, commonService) {  // do something...  }, link: function (scope, element, attris) { } }});

tableTem.html文件代码如下:

<div> <table class="table table-hover table-bordered"> <thead>  <tr>  <th ng-if="tableData.multiSelect">   <input type="checkbox" id="check-all" ng-model="itemsChecked">   <label for="check-all" class="fa" ng-class="{'fa-square-o': !itemsChecked, 'fa-check-square-o': itemsChecked }" aria-hidden="true">   </label>  </th>  <th ng-repeat="item in tableData.thead">{{item}}</th>  </tr> </thead> <tbody>  <tr ng-repeat="item in tableData.items" ng-click="selectItem(item)" ng-init="item.selected = false" ng-class="{'selected': item.selected}">  <td ng-if="tableData.multiSelect">   <input type="checkbox" id="check_{{$index}}" ng-model="item.selected">   <label for="check_{{$index}}" class="fa" ng-class="{'fa-square-o': !item.selected, 'fa-check-square-o': item.selected }" aria-hidden="true">   </label>  </td>  <td ng-repeat="name in tableData.theadName">   {{item[name]}}     </td>  </tr> </tbody> </table></div>

控制器文件代码如下:

var myBasis = angular.module("myBasis",["myCommon"]);myBasis.controller("myCtrl", function ($scope) { $scope.tableData = { multiSelect: false, pageSize: [10, 20, 50], thead: ["导入时间", "导入名称", "结果", "操作"], theadName: ["importDate", "name", "result", "oper"] };});

以上,完成了表格展示数据的功能,可是在表格列里面,经常有对某行数据的操作,而这些操作我们同样需要以html的形式插入到表格里面,并且这些html中,还会有ng-click等之类的指令,或者是自定义的指令。比如:"<a href='javascript:;' ng-click='show(item)'>查看信息</a>"; 这类的html,插入到td中,会以html代码展示出来,并不会转换成html。

在网上查阅了方法后,找到了一个转html的解决办法,增加一个过滤器,如下:

myCommon.filter("trusted", function ($sce) { return function (html) { if (typeof html == "string") {  return $sce.trustAsHtml(html); } return html; }});

然后修改temp文件中的代码:

 <td ng-repeat="name in tableData.theadName"> <span ng-bind-html="item[name] | trusted"></span></td>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选