angularjs - 我想在每行之前添加行号,我正在使用 angularJs json 过滤器

标签 angularjs json angularjs-filter pre line-numbers

我有显示 json 对象的代码预览。 我想在每行之前添加行号。该代码运行良好,但我无法在每行之前添加行号。 我正在使用 angularJS 1.5.8。为了显示 json 我使用 angularJS json 过滤器。

我希望它看起来像这样:

1 | {
2 |    "a": 1,
3 |    "b": 2
4 | }

现在看起来像这样:

{
    "a": 1,
    "b": 2
} 

我的 html 模板:

<pre id="previewArea"><code>{{ $ctrl.myObj | json : 4}}</code></pre>

我的 angularJS 组件:

ctrl.myObj={
        a:1,
        b:2
    }

最佳答案

这里有一个解决方法,它涉及用新行分解 json 过滤数据,然后用 span 连接每一行:

angular.module('app', [])
  .controller('Controller', function($scope, $filter, $sce) {
    $scope.sampleObj = {
      "a": 1,
      "b": 2
    }

    $scope.myObj = '<span>' + $filter('json')($scope.sampleObj).split("\n").join('</span><span>') + '</span>';
    $scope.myObj = $sce.trustAsHtml($scope.myObj);
  })
pre {
  background: #303030;
  color: #f1f1f1;
  padding: 10px 16px;
  border-radius: 2px;
  border-top: 4px solid #00aeef;
  -moz-box-shadow: inset 0 0 10px #000;
  box-shadow: inset 0 0 10px #000;
}

pre span {
  display: block;
  line-height: 1.5rem;
  counter-increment: line;
}

pre span:before {
  content: counter(line);
  display: inline-block;
  border-right: 1px solid #ddd;
  padding: 0 .5em;
  margin-right: .5em;
  color: #888
}
<!DOCTYPE html>

<head>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
  <script src="script.js"></script>
</head>

<body ng-app="app">
  <div ng-controller="Controller">
    <pre class="code" ng-bind-html="myObj">
    </pre>
  </div>
</body>

</html>

关于angularjs - 我想在每行之前添加行号,我正在使用 angularJs json 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50169741/

相关文章:

javascript - Angular $http.post 将日期更改为 UTC 日期

javascript - 如何检查 Twilio.Device 处理程序是否已经存在

arrays - Golang 通用 JSON 编码

javascript - AngularJS ng-隐藏在嵌套字典中

javascript - 过滤器在 ng-repeat 中不起作用

javascript - 带有 typescript 的 Angular 过滤器在缩小后不起作用

javascript - 具有不存在属性默认值的 Angular 服务

css - 如何在所有内容之上显示居中的 md-progress-circular

javascript - 我如何使用angularJS从JSON结果中提取对象

javascript - Angular 5 : read local json file