Tips for updating information in a JSON server and showcasing it on your HTML page using Angular/Ionic

Attempting to develop a prototype restaurant app using Angular/Ionic 1. Created a modal for adding comments and pushing them to a json server. Struggling to render the new comment on the HTML page after successful addition to the json file. The page freezes after closing the modal. Need assistance in displaying the newly added comment.

Below is the modal HTML code:

    <ion-modal-view>
<ion-header-bar>
  <h1 class="title">Add Comments</h1>
   <div class="buttons">
        <button class="button button-stable button-clear" ng-click="closeComment()">Close</button>
    </div>
</ion-header-bar>

  <ion-content>
    <form id="addCommentForm" name="addCommentForm" ng-submit="submitComments()">
    <div class="list">
        <label class="item item-input item-select">
            <span class="input-label">Rating</span>
            <select ng-model="mycomment.rating">
                <option ng-repeat="n in [1,2,3,4,5]" value="{{n}}">
                    {{n}}</option>
            </select>
        </label>
        <label class="item item-input">
             <span class="input-label">Name</span>
            <input type="text" ng-model="mycomment.author">
        </label>
        <label class="item item-input">
            <span class="input-label">Comment</span>
            <textarea placeholder="" ng-model="mycomment.comment"></textarea>
        </label>
        <label class="item">
             <button class="button button-block button-positive" type="submit">Add Comment</button>
        </label>
    </div>
</form>
</ion-content>

Controller code as below:

     $scope.mycomment = {rating:5, comments:"", author:"", date:""};

           $ionicModal.fromTemplateUrl('templates/dish-comment.html', {
              scope: $scope,
              animation: 'slide-in-up'
            }).then(function(modal) {
              $scope.addComment = modal;
            });
            $scope.openComment = function() {
              $scope.addComment.show();
              $scope.popover.hide();
            };

            $scope.closeComment = function() {
              $scope.addComment.hide();
            };


            $scope.submitComments = function () {

            $scope.mycomment.date = new Date().toISOString();
            console.log($scope.mycomment);

            $scope.dish.comments.push($scope.mycomment);
         menuFactory.getDishes().update({id:$scope.dish.id},$scope.dish);


            $scope.mycomment = {rating:5, comment:"", author:"", date:""};
            $scope.addComment.hide();
        }
            $scope.$watch('dish.comments', function() {
                $scope.test = $scope.dish.comments;
                console.log($scope.test);
                });

Displaying the content on the HTML page:

    <div class="card">
      <div class="item item-body item-text-wrap">
           <img class="full-image" ng-src="{{baseURL+dish.image}}" alt="Uthappizza">
            <h2>{{dish.name}}
             <span style="font-size:75%">{{dish.price | currency}}</span>
            <span class="badge badge-assertive">{{dish.label}}</span></h2>
            <p>{{dish.description}}</p>
      </div>
  </div>
  <div class="row">
        <div class="col col-offset-10">
               <h4>Customer Comments &nbsp;&nbsp;&nbsp;
                   <small>Sort by: &nbsp;
                         <input type="text" ng-model="orderText">
                      </small></h4>
                <ul class="list">
                    <li ng-repeat="comment in dish.comments | orderBy:orderText">
                      <blockquote>
                         <p>{{comment.rating}} Stars</p>
                         <p>{{comment.comment}}</p>
                         <footer>{{comment.author}}, {{comment.date | date:'MMM. dd, yyyy'}}</footer>
                      </blockquote>
                    </li>
                </ul>
        </div>
  </div>

JSON file:

     {
"id": 3,
"name": "ElaiCheese Cake",
"image": "images/elaicheesecake.png",
"category": "dessert",
"label": "",
"price": "2.99",
"description": "A delectable, semi-sweet New York Style Cheese Cake, with Graham cracker crust and spiced with Indian cardamoms",
"comments": [
  {
    "rating": 5,
    "comment": "Imagine all the eatables, living in conFusion!",
    "author": "John Lemon",
    "date": "2012-10-16T17:57:28.556094Z"
  },
  {
    "rating": 4,
    "comment": "Sends anyone to heaven, I wish I could get my mother-in-law to eat it!",
    "author": "Paul McVites",
    "date": "2014-09-05T17:57:28.556094Z"
  },
  {
    "rating": 3,
    "comment": "Eat it, just eat it!",
    "author": "Michael Jaikishan",
    "date": "2015-02-13T17:57:28.556094Z"
  },
  {
    "rating": 4,
    "comment": "Ultimate, Reaching for the stars!",
    "author": "Ringo Starry",
    "date": "2013-12-02T17:57:28.556094Z"
  },
  {
    "rating": 2,
    "comment": "It's your birthday, we're gonna party!",
    "author": "25 Cent",
    "date": "2011-12-02T17:57:28.556094Z"
  },
  {
    "rating": "3",
    "comments": "Wonderful",
    "author": "Henna",
    "date": "2017-01-12T11:20:04.825Z"
  }
]

Experience the issue via recording of the app screen:

    https://i.sstatic.net/2lQhI.gif

Answer №1

Your code is looking pretty good overall, but there's one small issue that needs to be addressed. You have both your modal instance and form named as $scope.addComment. In Angular, the form is stored in a scope variable using its name, so essentially you're trying to save both the form and modal in the same variable.

To fix this, you should change either the modal or form's name and give it another try. It's likely that when you submit the form, it's being saved in $scope.addComment which overrides the modal instance, making it impossible to close the modal afterwards.

EDIT: It appears there is a known unresolved issue with Ionic popover and Ionic modal interactions. To work around this, you need to close the popover before opening the modal, delaying the modal's opening until the next cycle. This can be accomplished using $timeout or preferably by utilizing a promise:

$scope.openComment = function() {
    $scope.popover.hide().then(openModal);
};

function openModal() {
    $scope.addComment.show();
}

Answer №2

Is your page getting stuck displaying older JSONS and not updating with the newest data? One solution could be using a $watch function to continuously monitor changes in the $scope and ensure that you are always displaying the latest inserted 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

Is there a way to retrieve a JSON request through a webview in Android Studio?

Hello, I am facing an issue while trying to retrieve a JsonRequest from a submit on a Webview. I have tried various codes but none seem to work for me as I don't have much experience in this area. Even though this question has been asked before, I sti ...

Chosen option - Selection Menu - Relational Database Language

I am currently working on a dropdown list that needs to be filled from a database: <TH> <FORM> <p>Department</p> <SELECT size="1" id="depart"> <OPTION> <?php ...

Changing Marker Color in Google Maps API

There are multiple Google Maps Markers colors based on certain conditions being TRUE or not. In addition, these Markers will change color when the mouse hovers over a division (a1,a2..ax). I want the Markers to revert back to their original color when th ...

Error: The function 'readAsDataURL' of 'FileReader' was unable to be executed as parameter 1 is not a 'Blob' type

My issue involves a javascript Filereader that is giving me an error Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'. It's a hit or miss situation. Sometimes it wor ...

Tips for injecting scripts into the head tag after an Angular component has been loaded

Currently, I am facing an issue with a script tag containing a Skype web control CDN. The script has been placed in the head section of my index.html file, but it is being called before the component that needs it has finished loading. Does anyone have a ...

Trouble toggling Reactstrap navbar in my TypeScript project using NextJS

I recently integrated Reactstrap into my NextJS TypeScript project and encountered an issue with the Navbar component. Despite following the example from the Reactstrap documentation, the mobile toggle menu does not open when clicked. Additionally, none of ...

Building a date conversion process using JavaScript

Is there a way to change this date format: Sun Jan 08 2012 00:00:00 GMT+0530 (Sri Lanka Standard Time) to look like this: 2012-01-08 using JavaScript? Thank you! Edit: I was working with ExtJS and discovered that there's an easier way to achiev ...

What is the best way to showcase content using Chakra-ui SideBar in a React Application?

After exporting the SideBar, I imported it into my App.jsx SideBar.jsx 'use client' import { IconButton, Avatar, Box, CloseButton, Flex, HStack, VStack, Icon, useColorModeValue, Text, Drawer, Draw ...

npm allows for multiple entry points for modules

I'm working on an NPM package and I'm curious about how to allow users to register multiple entry points. This way, they have the option to import either the entire library or just specific parts that they need. For instance, importing the compl ...

Optimize your mobile experience by creating a notification menu that is scrollable and fixed in position

Recently, I purchased Moltran, but encountered a major issue: The notification menu disappears on mobile devices, which is not ideal for me. After some research, I discovered that removing the hidden-xs class from the li notification element can solve this ...

Tips for deserializing JSON with random string keys in Unity's C# using JsonUtility?

When working with Unity and C#, utilizing JsonUtility is key. Let's say we have a JSON string like this: { "1,1":"dd", "2,1":"abc", "2,2":"123" } The number and content of keys can vary. How can we deserialize this JSON and map it to our ...

How can the button press, release, drag, and drop events be implemented in Ionic?

I have been working on adding a recording feature that allows for recording when a button is pressed and stops when it is released. I decided to use the ionic-long-press plugin for this functionality. However, I have noticed that it does not support drag ...

Creating objects with Javascript looping

Here is the JSON data that I am working with: [ { "name": "sp5", "damage": "68", "penetration": "35", "class1": "6", "class2": "6", "class3": "6", "class4": "5", "class5": "3", "class6": "2" }, { "name": "sp6" ...

How to Retrieve the Absolute Index of the Parent Column Using jQuery Datatables

I recently developed a custom column filtering plugin for datatables, but I've encountered a minor issue. Within each column footer, I have added text inputs, and now I am trying to capture their indexes on keyup event to use them for filtering. In ...

What is the best way to filter out empty arrays when executing a multiple get request in MongoDB containing a mix of strings and numbers?

I am currently working on a solution that involves the following code: export const ProductsByFilter = async (req, res) => { const {a, b, c} = req.query let query = {} if (a) { query.a = a; } if (b) { query.b = b; } if (c) { ...

Transfer the scroll top value from a textarea to a div element

In the parent div, there is a div and a textarea. I am attempting to synchronize the scrollTop value of the textarea with the div so that they move together when scrolling. The issue arises when I input text into the textarea and hit enter for a new line. ...

Create a vibrant PNG image background that changes dynamically based on the dominant color of the

Is it possible to dynamically set the background color of a PNG image, either white or black, based on the dominant color in the image? For example, this image should have a dark background: https://i.stack.imgur.com/cerjn.png And this one should have a ...

Embedding $sce functionality within a controller

I am facing a challenge where I have HTML content coming in as a string and I need to render it. After exploring options, I am considering using ng-bind-html, which requires $sce to be injected into the controller. Most of the examples I found online show ...

What is the best way to remove a parent app.js element from a child component?

When I click the delete button, my intention is to filter an array in the parent app.js component and remove a specific item. However, I keep encountering a Typescript error stating Cannot assign to read only property 'message' of object 'Sy ...

The Observer cannot be displayed in the console when using console.table

https://i.sstatic.net/2yPsa.png Snippet: console.log(this.data) When using console.table with the parameter Observer, the output in the console shows ellipsis. Is there a way to display the final value instead? ...