Angular ng-repeat is incompatible with the JSON parser

I am facing an issue with accessing JSON objects and setting values into Angular Ui-grid. The problem arises when some of the fields in my JSON object are actually JSON strings. I attempted to convert these fields into JSON objects using JSON.parser, but encountered a situation where no data was displayed and no error message was generated.

JSON Object

[  
   {  
      "jobId":"efe0ace0-8ed9-45ff-9232-974cbdc89b86",
      "jobType":"TestJob",
      "nextRun":"N/A",
      "lastRun":"2015-11-26 13:26:10.664",
      "createdDate":"2015-11-26 13:26:10.664",
      "executor":"g",
      "JobDetails":"{\"environment\":\"TQ\",\"additionalEmailRecipients\":[\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1770397057707a767e7b3974787a">[email protected]</a>\"],\"extraParams\":{\"PlanFileName\":\"RestAPI.xml\"}}",
      "status":"active",
      "elapsedTime":"1 day ago"
   }
]

I made an attempt to convert the JobDetails field into a JSON object inside the cell template.

var testPlantemplate ='<div><ul><li ng-repeat="testPlans in JSON.parse(row.entity.JobDetails)">{{testPlans.environment}}</li></ul></div>';

Complete JavaScript Script

'use strict';
var tepTableModule = angular.module('test',
        [ 'ngAnimate', 'ngTouch','ui.grid','ngResource' ]).factory('Service',
        function($resource) {
            return $resource('/api/job/jobs', {});
        });

    tepTableModule
    .controller(
            'tepTableCtrl',
            function($scope, Service) {
                $scope.TestData = Service.query();

        //This doesn't work     
               var testPlantemplate ='<div><ul><li ng-repeat="testPlans in JSON.parse(row.entity.JobDetails)">{{testPlans.environment}}</li></ul></div>';

                $scope.tableData = {
                    data : 'TestData',

                    groupsCollapsedByDefault : true,


                    enablePinning : true,
                    columnDefs : [ {
                        field : 'jobId',
                        displayName : 'jobId',
                        visible : false
                    },  {
                        field : 'JobDetails',
                        displayName : 'Test Plan Name',
                        cellTemplate : testPlantemplate,
                        visible : true
                    },
                     {
                        field : 'jobType',
                        displayName : 'JobType',
                        visible : true
                    },
                     {
                        field : 'environment',
                        displayName : 'Environments',
                        visible : true
                    },
                     {
                        field : 'status',
                        displayName : 'Status',
                        visible : true
                    },
                    {
                        field : 'elapsedTime',
                        displayName : 'LastRun',
                        visible : true
                    },
                    {
                        field : 'JobDetails.additionalEmailRecipients',
                        displayName : 'Email Recipients',
                        visible : true
                    },
                    {
                        field : 'executor',
                        displayName : 'Executor',
                        visible : true
                    }
                    ],
                    sortInfo: {
                          fields: ['elapsedTime'],
                          directions: ['desc']
                        },
                    plugins : [ new ngGridAutoRowHeightPlugin() ]
                };

                $scope.changeGroupBy = function(group) {
                    $scope.gridOptions.groupBy(group);
                }
                $scope.clearGroupBy = function() {
                    $scope.gridOptions.$gridScope.configGroups = [];
                    $scope.gridOptions.groupBy();
                }

            });

I would appreciate any advice on how to access the JobDetails within the ng-repeat and set it into the UI grid successfully.

Answer №1

Implement a new function within the scope

$scope.convertToJSON=function(str){
  return JSON.parse(str);
}

Next, utilize this function in the template

var sampleTemplate ='<div><ul><li ng-repeat="samples in convertToJSON(row.entity.JobDetails)">{{samples.environment}}</li></ul></div>';

JSFIDDLE

Answer №2

Have you attempted using stringify() to escape all "/" characters?

    var testPlantemplate ='<div><ul><li ng-repeat="testPlans in JSON.stringify(row.entity.JobDetails)">{{testPlans.environment}}</li></ul></div>';

Take a look at this link...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Tween animations with Three.js

I have some queries regarding tween js within three.js. Below is the code snippet where the particles are generated as shown in the image: Image 1 // Code snippet for initializing var scene; var renderer; var container; var stats; var sphere; // Omitted ...

iOS Simulator offers a range of both offline and online events for testing purposes

I have been working on a phonegap 3.3 application that incorporates angularjs. When testing the application in my browser, I am successfully able to detect and respond to 'offline' and 'online' events. However, when I switch to the ios ...

Use the react-loadable library to dynamically import modules from multiple exported classes in JavaScript

Struggling to import CustomButton from a MyButton.js file using react-loadable? Can't seem to make it work in Home.js? Let's figure this out together! Solution for MyButton.js: import { CustomButton, BUTTON_STYLE, BUTTON_TYPE, BUTTON_SI ...

JavaScript Function for Finding the Time Difference Between Two Dates (in Years, Days, Hours, or Less than One Hour)

I need to calculate the time difference between 2 dates and display it. If the difference is greater than a year, show the number of years only. If it's more than a day, show the number of days. If it's less than a day, show the number of hours. ...

Retrieve a document through Django's rest framework after verifying the user's credentials

Currently, I'm immersed in a project employing Django as the backend. My focus lies on utilizing Django Rest Framework to manage an API for downloading files. @detail_route(methods=['GET'], permission_classes=[IsAuthenticated]) def test(sel ...

"Error: The property $notify is not found in the type" - Unable to utilize an npm package in Vue application

Currently integrating this npm package for notification functionalities in my Vue application. Despite following the setup instructions and adding necessary implementations in the main.ts, encountering an error message when attempting to utilize its featur ...

The performance of the Ajax Jquery remove function leaves something to be desired

My table has items with a delete button for each row. To achieve this, I created the following Ajax function: $(document).ready(function() { $(".destroy-device").click(function(e) { e.preventDefault(); var id = $(this).attr("data-id"); $.aj ...

Tips for sending a unique button ID to a jQuery click function

Within a table row of a dynamically generated table, I have multiple buttons each with its own functionality. My goal is to figure out how to pass the specific button ID to the onclick event of that table row when one of these buttons is clicked. $(&apos ...

AngularJS referrer URL functionality allows developers to capture and utilize the

I am working in angularjs and have a controller. Depending on the referrer URL, I need to display a message. Is there a built-in function in AngularJS that can help me achieve this without having to write any extra service? ...

Transforming JSON date format to a different one using Jackson libraries

My spring boot 1.3.5 application is using jackson with the dependency "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.5.0". Encountering an issue when a user inputs a date value in a format different than expected (mm/dd/yyyy) during a POST requ ...

Display the information contained within an array in a table using React

I have two arrays: one named formData and the other state array. const [formData, setFormData] = useState([]); let ure = [{}] useEffect(() => { axios .get("/api/listUre") .then((res) => { console.log(res.data ...

Demonstration of integrating services into Angular 1.5 components

Could someone provide an example of how to use services with Angular 1.5 components? I am attempting to inject a service into an Angular 1.5 component, but I'm encountering issues. For instance, I have a login component structured like this: class ...

php request for user to download pdf file

I am encountering an issue with the binary pdf file received from an angular $http.get request. I am attempting to trigger a dialog box to prompt the user for downloading the file using readfile() function, however, the dialog does not show up. Is there ...

What is the best way to adjust the spacing between components to prevent overlapping?

I'm looking to adjust the spacing between the textfield and button components so they don't overlap. I want to create some space between them but I'm not sure how to achieve this. I'd like to have at least 1-2 spaces added between the ...

Successfully running npm update on a Mac seemed to have updated the package, however, the

I needed to upgrade my npm version using the following command: npm install npm@latest -g After running the above command, I encountered the following output: /Users/ariful.haque/.npm-global/bin/npm -> /Users/ariful.haque/.npm-global/lib/node_modules ...

Updating data on the next page with the ID from the previous page in Ionic

In my Ionic application with a SQLite database, I need to transfer data from the "Data Form" page to the "Add More Info" page using the same ID. This data needs to be loaded on the "Add More Info" page before any controller is executed. Once on the "Add Mo ...

What causes async / await function to be executed twice?

I am currently developing a node.js application using express. In this project, I have implemented a regular router that performs the following tasks: It searches for the myID in the DB, If the myID is found, it attempts to execute the addVisit() functio ...

When utilizing Laravel to send a JSON response, a strange issue occurs where an extra single quote (`'`) and double quote (`"`) are included in the output: `'{"status":500,"

Utilizing jQuery's $.ajax function to make ajax requests to my Laravel 5.1 API. I am attempting to display the error response from the server, but facing difficulty in parsing the response due to an unexpected ' at the beginning of the responseT ...

What is the best way to showcase a set of paired arrays as key-value pairs?

Currently, I am developing a client in React that is responsible for receiving streaming data that represents objects from the back end. The client's task is to parse this data and dynamically construct the object as a JavaScript data structure, typic ...

What is the most effective method for incorporating multi-line breadcrumb links in a React application?

I am currently working on implementing a multiline breadcrumb link feature for mobile and tablet devices. As users navigate through multiple folders, I need to handle scenarios where the number of links exceeds the maximum allowed in the breadcrumb contain ...