Incorporating list updates in Angular

I am brand new to angular and currently working on adding functionality to a list. I have a couple of queries.

  1. Why does the console.log output for $scope.newChat show as undefined?
  2. Is newChat accessible to the sendChat() function due to variable hoisting?

Template

<ion-list>
      <ion-item class="item-remove-animate item-avatar item-icon-right" ng-repeat="chat in chats" type="item-text-wrap" href="#/tab/chats/{{chat.id}}">
        <img ng-src="{{chat.face}}" >
        <h2>{{chat.name}}</h2>
        <p>{{chat.lastText}}</p>
        <i class="icon ion-chevron-right icon-accessory"></i>

        <ion-option-button class="button-assertive" ng-click="remove(chat)">
          Delete
        </ion-option-button>
      </ion-item>
      <ion-item >
        <form ng-submit="sendChat(newchat)"> <!-- this line in query 2 -->
            <label class="item item-input">
              <input type="text" placeholder="What do you need to do?" ng-model="newchat.lastText">
            <button type="submit" class="button button-right button-positive">Send</button>
            </label>
          </div>
        </form>
      </ion-item>
    </ion-list>

controller

.controller('ChatsCtrl', function($scope, Chats) {
  $scope.chats = Chats.all();
  $scope.remove = function(chat) {
    Chats.remove(chat);
  }
  $scope.sendChat = function(newchat){
    Chats.set(newchat);
    console.log($scope.newchat); //this is the question in query 1
    newchat.lastText  = "";
  }
})

Answer №1

1) When console.log is used on $scope.newChat, why does it return undefined?

When you access newChat on the scope using console.log($scope.newchat);, try logging it without the scope like this: console.log(newchat);. Both methods are the same because newChat in ng-model makes it available on the scope. Check the console after clicking the send button in the demo below.

2) Is newChat available for the sendChat() call due to variable hoisting?

No, it is available due to ng-model data binding.

Demo

angular.module('myApp',[])
.controller('ChatsCtrl', function($scope) {
  //$scope.chats = Chats.all();
  $scope.remove = function(chat) {
    //Chats.remove(chat);
  }
  $scope.sendChat = function(newchat){
   // Chats.set(newchat);
    console.log($scope.newchat); //this line in question 1
    newchat.lastText  = "";
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ChatsCtrl"> <form ng-submit="sendChat(newchat)"> <!-- this line in question 2 -->
            <label class="item item-input">
              <input type="text" placeholder="What do you need to do?" ng-model="newchat.lastText">
            <button type="submit" class="button button-right button-positive">Send</button>
            </label>
         
        </form>
     
 </div>

Answer №2

update your controller with the code below

.controller('MessagesCtrl', function($scope, Messages) {
  $scope.newMessage = {};
  $scope.messages = Messages.getAll();
  
  $scope.deleteMessage = function(message) {
    Messages.remove(message);
  }
  
  $scope.sendMessage = function(newMessage){
    Messages.add(newMessage);
    console.log($scope.newMessage); //you can now access $scope.newMessage
    newMessage.text = "";
  }
})

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

Exploring the capabilities of storing and retrieving nested objects within a React database

I'm having trouble retrieving nested items from my database. This is how my database is structured: GET /dwelling/room/ [ { "room_id": 1, "room_name": "Living Room", "room_data": [ { "id": 1, ...

JavaScript program failing to execute

Seeking to incorporate a read more and read less feature that activates on click for my articles application using Django. However, encountering an issue where my JavaScript code does not work when the read more link is clicked. Below are the relevant fil ...

Child object in Three.js does not inherit transformation from its parent

Consider a scenario where there is a main object with multiple child objects in a given scene. Update: Here is the code snippet for creating a mesh (assuming the scene and camera are already set up). Code snippet for creating the parent group: var geome ...

ways of exporting and using arrays in Node.js

Constantly receiving the "undefined" error in main.js: var dbAccess = require('../dao/dbAccess'); dbaInstance = new dbAccess(); var wordPool = dbaInstance.getWordPool(); console.log (wordPool); The contents of "dbAccess.js" are as follows: var ...

Unable to create module instance, despite correct module definition

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="../angular/angular-1.6.7/angular.js"/> <script src="../angular/angular-1.6.7/angular-route.min.js"/> <!--script type="text/ja ...

Automatic resizing of line charts in Angular with nvd3

I'm currently utilizing AngularNVD3 directives. Referencing the example at: https://github.com/angularjs-nvd3-directives/angularjs-nvd3-directives/blob/master/examples/lineChart.with.automatic.resize.html <!-- width and height have been removed f ...

Is there a way to retrieve information from a different object?

Access the code on Plunker I am working with two data structures - ingredients and recipes [{ "id":"1", "name": "Cucumber" }, .. ] and [{ "id":"1", "name": "Salad1", "recipein":[1, 3, 5] }, { ... } ] My goal is to ...

What is the reason behind JavaScript objects lacking a toJSON() method?

According to information from http://www.json.org/js.html, JavaScript objects can specify how they are serialized by JSON.stringify() through the use of a toJSON() method. It is interesting to note that numbers and strings appear to have this method, but f ...

What is the best way to differentiate the handling of a 401 Unauthorized response from other errors within an Angular 8 service that utilizes RxJS?

My REST API implementation requires an access token for user identification with each call. If the token is missing or expired, the endpoint returns a 401 UNAUTHORIZED response. There are instances where I make API calls using a timer in my service class: ...

Guide to filling a dropdown menu by aligning with the text it contains?

I've set up two dropdown select boxes below that are exactly the same: HTML <select id="ddl1" name="ddl1"> <option value="1">TEXT 1</option> <option value="2">TEXT 2</option> <option value="3">TEXT 3&l ...

Different from Window.Print()

I am looking to implement a print button that will trigger the printing of the entire webpage when clicked. I have been attempting to achieve this using Window.print() in JavaScript, but I encountered an issue where the link stops working if the print bu ...

Leverage Express JS to prevent unauthorized requests from the Client Side

Exploring the functionalities of the Express router: const express = require("express"); const router = express.Router(); const DUMMY_PLACES = [ { id: "p1", title: "Empire State Building", description: "One of the most famous sky scrapers i ...

Creating a seamless connection between a nodejs backend and a frontend interface

I'm facing an issue with my CRUD app developed using nodeJs. The app interacts with a mysql database to perform Create, Insert, Delete, and Read operations. Here's an example of a read operation: app.get('/run',(req,res) => { con ...

Animating three-dimensional objects using Three.js in real-time

I have been working with three.js and have successfully animated some objects using the animate() function. Here's a snippet of my code: function animate(){ object.position.z++; } The issue I'm facing is that this function is called every r ...

Angular directive for D3 chart not displaying on the page

While working on a D3-based angular directive inspired by this code pen Here is my implementation. Check out the Codepen link angular.module('myApp', []). directive('barsChart', function ($parse) { var directiveD ...

Expanding parent nodes in Jstree to load child nodes dynamically (json)

I am trying to optimize the performance by loading the child nodes of a parent node only after clicking on that specific parent node. It is important because there are many child nodes, so this method helps in keeping the performance high. Currently, I ha ...

The Functionality of $rootScope.$broadcast with Dual Arguments

I've been reading through this interesting article: https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec#.rlvow9x66 In an attempt to adapt their AuthInterceptor, I made modifications to handle ...

Incorporating a personalized event into a directive

I've developed a unique custom directive that generates a field within a larger form. To simplify, here's a snippet of the code: .directive('entityField', function () { return { restrict: 'E', scope: { ...

Issue with dropdown list functionality in Internet Explorer not functioning correctly

I am experiencing an issue with my dropdown lists. When selecting an item from the first dropdown list, it should not be available in the second dropdown list. To achieve this functionality, I have implemented jQuery code like the following: $(document).r ...

Troubleshooting issue with Express.json() functionality in the latest release of version 4.17

I'm currently exploring the MEAN stack and I am focused on performing CRUD operations. However, when I send data in the request body from Angular to the server, I end up receiving an empty request body. I'm unsure of where I might be making a mis ...