简体   繁体   中英

iterating over json object of arrays of objects, trusting one key's value as HTML in Angular

I have the JSON schema below, and I'm trying to iterate over each object's description and trust it as HTML so I can show the link in the application:

{
  "notes": {
    "long random ID number 1": [
     {
        "name": "test 1",
        "description": "<a href='http://google.com'>google</a>"
     }
    ],
    "long random ID number 2": [
      //more objects with names and descriptions
    ]
  }
}

Inside of notes, there are many arrays of JS objects with the key being a long, random ID. How can I iterate over each array of objects regardless of the key, and run Angular's $sce.trustAsHtml() on the link so it shows in the UI?

Edit:

var notesKeys = Object.keys($scope.requirements.notes);

for(var key in notesKeys)
{
    for(var note in $scope.requirements.notes[key])
    {
        $sce.trustAsHtml(note.description);
        $sce.trustAsHtml(note.name);

        console.log(note.description);
        console.log(note.name);
    }
}

I guess something like that can do the trick :

$scope.links = [];
//Get the keys of your hash, object is your complete object
var notesKey = Object.keys(object.notes)
//iterates over keys in notes
for(var i=0; i < notesKey.length; i++){
  // iterates over each object
  var notes = object.notes[notesKey[i]];
  for (var j=0; j < notes.length ; j++){
   //You have your object so do what you like
   $scope.links.push($sce.trustAsHtml(notes[j].description));
  }
}

In your html use ng-repeat and ng-bind-html, depending of what you want :

<div ng-repeat="link in links" ng-bind-html="link"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM