2

I have code preview that displays json object. I want to add line number before each line. The code is working great, but I'm unable to add the line number before each line. I'm using angularJS 1.5.8. In order to display the json I'm using the angularJS json filter.

I want it to look something like that:

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

now it looks like that:

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

My html template:

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

My angularJS component:

ctrl.myObj={
        a:1,
        b:2
    }
Learning
  • 21
  • 3
  • Please notice that the different is that in order to display the json i'm using the angularJS json filter. – Learning May 05 '18 at 16:40

1 Answers1

2

Here is a work around,It involves exploding the json filtered data with new line and then joining each line with 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>
Gaurav Srivastava
  • 3,232
  • 3
  • 16
  • 36