Trouble with adding an object to an array in AngularJS

I'm having trouble pushing an object to an array. I'm trying to push the comments object (values from forms) on submit click, into dish.comments in dishDetailController. The ng-controller="DishCommentController" is nested inside ng-controller="dishDetailController". Any idea where I might be making a mistake?

main.html

<div class="row row-content" ng-controller="dishDetailController as menuCtrl">
    <div class="col-xs-12">
        <ul class="media-list">
            <li class="media">
                <div class="media-left media-top">
                    <a href="#">
                        <img class="media-object img-thumbnail"
                         ng-src={{menuCtrl.dish.image}} alt="Uthappizza">
                    </a>
                </div>
                <div class="media-body">
                    <h2 class="media-heading">{{menuCtrl.dish.name}}
                     <span class="label label-danger">{{menuCtrl.dish.label}}</span>
                     <span class="badge">{{menuCtrl.dish.price | currency}}</span></h2>
                    <p>{{menuCtrl.dish.description}}</p>
                </div>
            </li>
            {{menuCtrl.dishes}}
        </ul>
    </div>
    <div class="col-xs-9 col-xs-offset-1">
          <div class="media-right"><h3 class="media-right">Customer Comments  &nbsp; &nbsp; &nbsp;<small>Sort By:
                 <input type="text" ng-model="sort"></small></h3></div><br>
        <ul ng-repeat="comments in menuCtrl.dish.comments | orderBy:sort">
            <blockquote>
                <div class="media-body">
                    <h3 class="media-heading">{{comments.rating}} Stars</h3>
                    <h4 class="media-heading"></h4>
                     <p>{{comments.comment }}</p>
                    <footer>{{comments.author}},<cite title="Source Title">{{comments.date | date:'MMM,dd,yyyy'}}</cite></footer>
                    <p><li></li></p>
                </div>
            </blockquote>
        </ul>
    </div>

    <div class="col-xs-9 col-xs-offset-1" ng-controller="DishCommentController as comment">
        <blockquote>
            ...
        </blockquote>
        <ul class="list-unstyled">
        </ul>
        <form class="form-horizontal" name="commentForm"
                ng-submit="submitComment()" novalidate>
            ...
        </form>
    </div>

app.js

'use strict';
    angular.module('confusionApp',[])

    .controller('dishDetailController', ['$scope', function($scope)  {
        ...
    }])

	.controller('DishCommentController', ['$scope', function($scope) {
		...
	}]
	

Answer №1

It appears that you may have overlooked creating the $scope.dish variable and only created the var dish = ... variable instead. Therefore, you won't be able to assign anything in this scenario!

Answer №2

Stumbled upon this while searching for JavaScript examples on how to clear arrays. The query is related to an assignment for a Coursera Course focusing on Angular JS.

It is unnecessary to utilize "as MenuCtrl" during the initialization of ng-controller if $scope is being used appropriately. This topic is explained in the course, and I suggest revisiting the material for better understanding. Solving the problem will prove challenging as only a portion of the solution has been implemented.

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

Retrieving the width and height of a DIV element using Javascript

Currently, I am attempting to retrieve the width and height of a div element as it is being changed by the user and then pass that data to another page. However, I am encountering difficulties in obtaining the width and height values. <script> $(fun ...

The function I created is having trouble connecting to the controller.js file

My JavaScript controller file function ServicesCtrl($scope) { console.log("Greetings from ServicesCtrl"); $scope.message = "Hello!"; } The main HTML file <html> <head> <title>The Complete Web Development Stack</ti ...

The significance of API Input Validation and Steering Clear of Lengthy Conditional Statements

Currently, I am working on ensuring that my API functions correctly even in cases of bad or missing data. At the moment, I have an if statement that checks for any missing inputs. If an input is missing, it returns false, otherwise there is a large else b ...

Create a new object in Three.js every x seconds and continuously move each object forward in the Z-axis direction

I am currently developing a Three.js endless runner game where the player controls a character dodging cars on a moving road. At this early stage of development, my main challenge is to make the hero character appear to be moving forward while creating the ...

Is RaphaelJS truly a vector-based tool?

Is it possible to position a circle at 50% of the width of the canvas using RaphaelJS without having to calculate the exact pixel value? I am looking for a simple way to place an element at half its container's width, but I'm not sure if this can ...

Determine if a specific identifier is already present using Javascript or Jquery

Is there a way to determine if an html tag with its specific id is present more than once in the code? This is my pseudocode for checking: if($('#myId').length > 1) { // It exists twice } ...

What is the method for displaying an image within an HTML div element?

Is there a way to include an image inside an HTML div tag when printing a document? Here's the method I've been using: Using HTML5: <div> <img src="/images/pag.jpg" alt="pagsanghan Logo" style="opacity: .8; height:100px; width:10 ...

JavaScript special character encoding techniques

I'm trying to create a function to remove special characters in my JavaScript code. However, whenever I try using chr(46), it throws a syntax error. Does anyone have any suggestions on how I can successfully implement chr(46) in my JS code? storageV ...

jinja2.exceptions.UndefinedError: The variable 'participant' has not been defined

I am currently in the process of developing a video chat web application using Twilio, and I have been following a tutorial on how to build the application: . However, I keep encountering an error mentioned in the title. It seems like I am trying to access ...

refuse to honor any outstanding commitments

My current scenario involves multiple promises in a service that utilize the $q service. I am looking for a way to reject all pending promises upon a location change in order to avoid running any chained promises. Is there a way to achieve this? Thank you ...

Effective and Sustainable Methods for Error Management in Node/Express API Endpoints

Throughout my experience with developing MEAN Stack applications and setting up APIs, I have encountered some uncertainty when it comes to handling errors within API Routes. If there are any inaccuracies in my explanation or if my concepts are flawed, ple ...

LeafletJS: The map container has already been initialized

In my Ionic 2 app, I am utilizing Leaflet. The app works perfectly fine when launched for the first time. However, if I navigate to another page and then return to the map page, I encounter the following exception: ERROR: Error: Uncaught (in promise): ERR ...

ReactJS is giving me an error message: "Uncaught TypeError: Unable to access property 'ownerDocument' since it is null."

Trying to create a bar chart using D3 and render it with React's render method. Below is my index.js file: import React from 'react'; import ReactDOM from 'react-dom'; import './Styles/index.css'; import BarChart from &a ...

Retrieve the value of a JavaScript variable

Currently, I am working on developing a web application that utilizes the Google Maps Direction API. Within a variable named summaryPanel.innerHTML, I store essential details about addresses and distances. I need to utilize the distance data for additional ...

Unable to locate the root element for mounting the component in Cypress with React

I am currently testing my react app, which was created using create-react-app, with the help of cypress. Unfortunately, I encountered an error that looks like this: https://i.stack.imgur.com/xlwbo.png The error seems to be related to trying to fetch an ...

Using the className prop in a React Component

Struggling to assign a classname to the material-ui Button component. Here are my failed attempts: Attempt 1: attributes.map((attribute, index) => { const classString = 'classes.button' + index; console.log(classString) return ( &l ...

State is not being updated by useState after the second API call in MUI and ReactJS

I encountered an issue while using the Material-UI Autocomplete component for a search box. The problem arises when fetching options from an API and passing them to the component. Initially, the dropdown displays the options correctly. However, upon closin ...

Passing variables through a promise chain and utilizing the finally method

My current endeavor involves constructing a log for an Express API, yet I am encountering difficulties in extracting the data for logging. I have successfully logged the initial req and res objects within the finally block, but I am uncertain about how to ...

Properly storing information in the mongoDB

Having trouble saving data in my Angular application correctly. Here is a snippet of my API code: .post('/type/add', function(req, res){ var type = new NewType({ type: req.body.type, subtype: req.body.subtype, }); type.save ...

Guide on creating a Sequelize query to retrieve all tasks linked to a specific user_id

I'm currently developing my first to-do list application using node express ejs and sequelize with sqlite Below is my sqlite.js file which contains the database schemas: const Sequelize = require("sequelize"); const sequelize = new Sequelize({ dia ...