在DOM中呈现表格后,表格中具有链接的AngularJS Linkify单元格

时间:2019-01-07 16:01:02

标签: javascript angularjs angularjs-1.6

我正在尝试操纵表格的html,以替换具有链接的单元格中的所有文本,并使用AngularJS单击<a>链接。

enter image description here

在加载DOM时,我有以下代码:

...
$("td").each(function (index) {
  if($(this).text())
  {
      $(this).text($ctrl.linkify($(this).text().toString()));
  }
});
...

$ctrl.linkify = function(text) {
  var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(urlRegex, function (url) {
         return '<a href="' + url + '">' + url + '</a>';
  });
}

但是,它不会将链接呈现为可点击的链接元素。

enter image description here

重要的一点是,该表是由第三方插件动态添加的,因此我只能在加载后 对其进行操作。因此,为什么在渲染表格后我在标题中提到了。

如何使用angular js链接单元格?还是使用sanitize呈现新的html?

1 个答案:

答案 0 :(得分:1)

您将其视为文本,因为ng-model或{{}}仅显示文本,您需要将它们显示为html,在这种情况下,您可以使用ngBingHtml指令。 / strong> 要使用它,您必须在项目中包含angular-sanitize,然后在表中将其以这种方式使用:

这是一个可行的例子

var editor = angular.module("editor",['ngSanitize']);
var app = angular.module('plunker', ['editor']);


editor.controller('EditorController', function($scope) {

    $scope.values = ['Normal text', 
                     'https://www.google.com/', 
                     'This is not a link'];
    $scope.replaceUrlWithATag = function(text){
      var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
      return text.replace(urlRegex, (url) => {return '<a href="' + url + '">' + url + '</a>'});
    }
});


editor.directive("editorView",function(){
  return {
    restrict :"EAC",
    templateUrl : "editor.html",
    scope : {
        content : "=editorView"
    },
    link : function(scope,element,attrs){
        
    }
  };
});

app.controller('BaseController', function($scope) {
  $scope.content = 'World';});
<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <script>document.write('<base href="' + document.location + '" />');</script>
  <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
  <link rel="stylesheet" href="style.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular-sanitize.min.js"></script>
</head>
<body>
  <div ng-controller="EditorController">
    <table class="table table-bordered">
        <tr>
            <th>ID</th>
            <th>Value</th>
        </tr>
        <tr ng-repeat="v in values">
            <td>{{$index}}</td>
            <td ng-bind-html="replaceUrlWithATag(v)"></td>
        </tr>
    </table>
</div>
</body>
</html>