How to showcase a single JSON object using AngularJS

When I retrieve news with a specific id from my REST API, using ng-repeat to display all news works fine. However, when I try to display a single object, this method does not work.

My route code:

.when('/displaynews/:id',{
    templateUrl: 'views/display.html',
    controller: 'NewsDisplayController',
    controllerAs: 'displaydash'
})

and the controller code:

.controller('NewsDisplayController',
    function($routeParams, NewsModel){

      var displaydash = this;
      var newsId = $routeParams.id;
      path = 'getNewsById/'+newsId;

      function getNewsById() {
          NewsModel.getNewsById().then(function (result){
              displaydash.news = result.data;
              console.log(displaydash.news);
          })
      }

      getNewsById();
})

Result from console.log:

Object { id="56f1ba6b275c8aa5bf4895d8", title="Tytul", text="Text", more...}

How can I display this in my HTML template?

I have tried displaying in the HTML file this way:

<p>{{news.title}}</p>
<p>{{news.text}}</p>

But it is not working

Answer №1

If you're looking to convert JSON to a string in Angular, you can do so by using the following code:

angular.toJson(JSONObj);

To implement this in a Controller, you can use the code below:

displaydash.news = result.data;
$scope.news = angular.toJson(displaydash.news);

For displaying the news in HTML, you can use the following code:

<p>{{news}}</p>

The error in your post seems to be related to accessing an undefined news object. Make sure to define a scope variable for it in order to access it easily:

 $scope.displaydash.news = result.data;

<p>{{displaydash.news.title}}</p>
<p>{{displaydash.news.text}}</p>

More information on angular.toJson can be found here: https://docs.angularjs.org/api/ng/function/angular.toJson

Answer №2

When result.data is identified as an object, wrap it within square brackets and assign it to news. Otherwise, simply use it as is.

 displaydash.news = typeof(result.data) == "object" ? [result.data] : result.data;

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

Package.json file is not included in Typescript

Each time I execute tsc, it converts the files to JS format successfully, except for package.json. I want this file included in my output directory. Currently, my tsconfig.json looks like this: { "exclude": ["node_modules"], "compilerOptions": { " ...

Utilize Django's TemplateView in ModelAdmin's add_view for seamless integration

As per the Django Admin site documentation, I have discovered that I can customize ModelAdmin.add_view to inject a custom view. My intention is to include a TemplateView to modify an admin page for adding or changing models. This unique view will feature ...

Once more: "The JSON object should be a string, bytes, or bytearray, not a list" encountered in the requests library

I'm struggling with a simple request and can't figure out what's wrong data1 = df.loc[N, 'online_raw_json'] print(type(data1)) print(data1) data1 = json.dumps(data1) print(type(data1)) print(data1) response = requests.post("h ...

`Error encountered when attempting to convert date with Angular JS filter`

Utilizing angular js filter in the controller for date formatting. A user selects a date from a uib-datepicker-popup. The goal is to format this date using ISO 8601 (yyyy-mm-dd) date format. Upon logging the user-selected date, the output is as follows: S ...

Unexpected behavior when using Async.map in conjunction with async.waterfall

Utilizing Async, I am using async.map() to connect my data array with a function and incorporating async.waterfall() within that function to execute functions in a series. However, the waterfall function is not functioning as anticipated. I have also attem ...

Transforming an AJAX call into a reusable function

My goal is to simplify my ajax calls by creating a function that can be reused. Although I'm unsure if I'm doing it correctly, I would like to attempt this approach. <script> $(document).ready(function(){ var reg_no=$("#reg_no").va ...

Unit testing promises in Angular using Jasmine

My goal is to create a unit test that demonstrates the process of combining two promises using $q.all in Angular, and then confirming that both promises are resolved simultaneously. describe("Application controller", function() { var scope; var ...

Tips for implementing a document ready function on a nested page within a larger full-page website

I am currently working on a website that utilizes fullpage.js, but the same principle applies to all single-page websites. I am trying to figure out how to implement the $(document).ready() function on a 'nested' page within the site. Since every ...

What is the best way to create a mapping function in JavaScript/TypeScript that accepts multiple dynamic variables as parameters?

Explaining my current situation might be a bit challenging. Essentially, I'm utilizing AWS Dynamodb to execute queries and aiming to present them in a chart using NGX-Charts in Angular4. The data that needs to appear in the chart should follow this fo ...

Every time Jquery tries to retrieve cookies, it consistently returns as undefined

Having trouble accessing Application cookies using jquery in my Asp.Net MVC App. Check out this Screenshot of Cookie and its Value. I've been trying to access the Cookie with $.cookie('ASP.NET_SessionId'); but it keeps returning "undefined" ...

Utilize jq to group and tally JSON data

I need to convert the JSON data provided into a CSV format that lists each unique "name" along with the total count of how many times it appears. Given data: [ { "name": "test" }, { "name": "hello" }, ...

Steps to retrieve the JSON response using newman

After successfully testing the endpoint on Postman, I exported it as a collection and now running it using Newman on Jenkins CI. Command: newman run <POSTMAN_COLLECTION>.json -r json,cli The response.json file is generated in the current direct ...

The state remains unaltered within the confines of the useState hook and useEffect function

I encountered a similar issue to the one discussed in this particular question The code provided was extensive, so I created a simplified version of the problem. (I apologize if there was an error in my approach) Essentially, I have a main component and ...

`Can I distribute configuration data to all components using a JavaScript file?`

My approach involves using config data to simultaneously affect the status of all components. I achieve this by importing the config object from the same JavaScript file and incorporating it into each component's data. It appears to work seamlessly, ...

Endless Loop Issue with Google Maps API Integration in NextJS-React

Currently struggling to troubleshoot an infinite loop issue in my React function component map. I've spent a considerable amount of time analyzing the code and suspect that it might be related to the useEffects, but I'm unable to resolve it. Atta ...

Instructions on how to insert the meta tag with the attribute "http-equiv" set to "REFRESH" and the content "0; URL="somedomain"" into a division on a

Trying to send an ajax request to a page that includes the following meta tag: <meta http-equiv="REFRESH" content="0; URL=https://www.ohterDomain.com/help?nodeId=2&view=content-only"> After making a successful ajax call, the correct content is ...

Ways to perform a force click on a span element when clicking on a glyphicon

There is a table cell containing two span elements: <span contentEditable=true class="editspan"></span> <span class="pencilspan glyphicon glyphicon-pencil pull-right"></span>" When clicking on span1, an input box appears for editi ...

Top method for utilizing overlays

Is there a method to randomly select hex codes for specific colors? I want to replicate the design in this image through coding. Image Here is the code I have so far: HTML <div id="group"> <div class="sub red panel"> </div><!--su ...

Mastering the use of Action.Submit in adaptive cards to simulate user input

I am trying to implement MessageFactory.SuggestedActions within my "welcomeCard" adaptive card. Essentially, in my adaptive card (welcome card), I have several buttons for the user to click on, each with an Action.Submit type. { "type" ...

Using Javascript to Highlight a Single Row in a Table

Greetings esteemed members of the skilled community at StackOverflow, I must humbly ask for your expertise in solving a dilemma that I am currently facing. The situation is as follows: I have a table generated from an SQL query, and it is crucial for the ...