0

referring to this plunker: https://plnkr.co/edit/kBoDTXmm2XbxXjpDA4M9?p=preview

I am trying to create a directive that takes an array of json objects, syntax highlights them and its that syntax highlighted element in the page.

I have had mixed results with different watching methods, but what I cant figure out in this one is why the same id:1 is showing all the way down the list, why not id:1, id:2, id:2, id:3 etc.

angular.module("ngjsonview",[]).directive('ngjsoncollection',['$sce', function(){
    'use strict';
    return {
        transclude: false
        ,restrict:'E'
        ,scope:{ d:'=',o:"=" }
        ,templateUrl: "./template.htm"
        ,controller:function($scope,$sce){
            var fnPretty = function(objData){
                if (typeof objData != 'string') { var strOut = JSON.stringify(objData, undefined, 2); }
                strOut = strOut.replace(/&/g, '&')
                    .replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;');
                return strOut.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
                    var cls = 'number';
                    if (/^"/.test(match)) {
                        if (/:$/.test(match)) { cls = 'key';} 
                        else { cls = 'string'; }
                    } else if (/true|false/.test(match)) { cls = 'boolean';} 
                      else if (/null/.test(match)) {cls = 'null'; }
                    return '<span class="' + cls + '">' + match + '</span>';
                });
            };

            $scope.html=$sce.trustAsHtml(fnPretty($scope.d));

            $scope.$watchCollection('d',function(arrData){
                $scope.arrHTML=[];

                for (var i = 0, len = arrData.length; i < len; i++) {
          $scope.arrHTML.unshift($sce.trustAsHtml(fnPretty(arrData[i])));
        }
            });
        }
    };

}]);
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299

1 Answers1

0

moving the timeout into a function helped with the specific problem I had

$scope.arrData=[];
function addIt(x) {
    $timeout(function(){
      $scope.arrData.push({id:x});
    }, 100);
}  
for(var i=0; i < 100; i++){
    addIt(i)
}