What is causing Angular to show undefined when using an object?

I'm relatively new to Angular development. I am currently working on a controller that involves validating user input for registration.

svs.controller('registrationCtrl', function($scope, validatorService) {
  $scope.$watch("registrationForm.email.value", function(newValue, oldValue) {
    if (validatorService.validateEmail(newValue))  {
      $scope.registrationForm.email.valid = true;
    } else {
      $scope.registrationForm.email.valid = false;
    }
  });
});

Within the corresponding view, there is an input field where users can enter their email address. The model used by Angular for this input is

$scope.registrationForm.email.value
. This setup has been confirmed by logging changes to the text input value using a simple console log statement within the $watch function.

The goal here is to structure an object under $scope.registrationForm with a format resembling this...

{
  email: {
    value: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2f5c40424a6a424e46436f5d4059464b4a5d014c4042">[email protected]</a>",
    valid: true
  }
}

The approach involves monitoring changes in the text area value, utilizing a service method for email validation, and updating the valid property of registrationForm.email to true when deemed valid.

However, encountering an error message...

TypeError: Cannot read property 'email' of undefined

I have not explicitly initialized registrationForm.email.valid in the JavaScript code, nor have I referenced it in the HTML markup.

Should I declare this property before assigning a value to it? What could possibly be causing this issue?

Answer №1

It is necessary to establish a property prior to configuring it.

$scope.email={};

Answer №2

If you want to simplify things, remember that angular is already equipped to handle it for you. Just add the attribute name to your form and input elements.

    <script>
  angular.module('emailExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.email = {
        text: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="731e1633160b121e031f165d101c1e">[email protected]</a>'
      };
    }]);
</script>
  <form name="myForm" ng-controller="ExampleController">
    <label>Email:
      <input type="email" name="input" ng-model="email.text" required>
    </label>
    <div role="alert">
      <span class="error" ng-show="myForm.input.$error.required">
        Required!</span>
      <span class="error" ng-show="myForm.input.$error.email">
        Not valid email!</span>
    </div>
    <tt>text = {{email.text}}</tt><br/>
    <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
    <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
    <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
    <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
    <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  </form>

For more information, check 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

Determining the successful completion of an ajax request using jQuery editable plugin

I recently started using Jeditable to enable inline editing on my website. $(".video_content_right .project_description").editable(BASE_URL+"/update/description", { indicator: "<img src='" + BASE_URL + "/resources/assets/front/images/indicator ...

What could be causing my problem with the add function?

I'm having trouble capturing the user input from modal input boxes and adding them to my state array. I've attempted to extract the values from the inputs and push them into a clone of the state array, then update the state with the clone. Howeve ...

Tips for incorporating jQuery UI into Angular 6

No matter how many methods I have tried from StackOverflow, I cannot seem to get jquery-ui to work in my angular 6 component. Here's what I've attempted: I went ahead and ran npm install jquery jquery-ui to install both jquery and jquery-ui. ...

What could be the reason for the component failing to update even after modifying the object's properties?

I have come across some related threads on Stack Overflow, but they only briefly mention using the spread operator. But why should we use it? In the code below, I am trying to update the firstName property of the user object, which is a state, when clicki ...

What is the process for deleting headers in a $http.get call and simultaneously including "application/json" and "text/plain" under the "Accept" header?

I'm relatively new to angularjs and I'm currently working on implementing some new features to an existing Angular JS application. The current API calls are quite intricate so I decided to make a direct call. Below is the code snippet for my new ...

What is the best way to transmit a response using JSON instead of Jade?

//This is the code in my index.js file var express = require('express'); var router = express.Router(); /* Display the home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Movie Datab ...

What should I do if one of my images fails to load after the previous one has loaded successfully?

My code is designed to create an animation using 3 canvases: one for the base image, one for the streamline wind map drawing, and another for an image covering part of the drawing. The following code displays the uploading of two images. var im ...

Exploring the world of HighCharts

I am trying to use Highcharts to calculate and visualize the magnitude of a complex number. Currently, my code is displaying the real and imaginary values separately on the graph. However, I seem to be facing issues with the "For loop" that I implemented ...

Tips for displaying Ajax response in a modal popup

I have a link that, when clicked, sends an AJAX request and successfully receives a response in the form of an HTML file, which I then append to a div. However, I want to display this div as a modal popup and I have attempted the following: In the HTML fi ...

I am not receiving the filtered data from the pagination directive

Hello everyone! I am currently utilizing the pagination directive from the following link: https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination However, I am encountering a challenge with retrieving filtered data. Typicall ...

What is the best method for sending the revised table information back to the server?

I have a table of data on a website that is dynamically populated using AngularJS: <table class="table table-bordered table-striped"> <thead> <tr> <th>Service</th> <th>Rate Type</t ...

The PHP function is returning an undefined value in JavaScript

I feel like there must be a simple solution to this problem that I just can't seem to find. Everything related to PHP search functions and queries is functioning properly, except for the fact that the data isn't displaying correctly in the text a ...

Utilizing JavaScript to retrieve data using AJAX

Having trouble sending emails through ajax on my website. The form is in a modal (using custombox), but all values being sent are null. How can I utilize getElementById in modal content? Link to custombox git's hub: https://github.com/dixso/custombox ...

Joi has decided against incorporating custom operators into their extended features

I am having trouble extending the joi class with custom operators. My goal is to validate MongoDB Ids, but when I try to use the extended object, I encounter the following error: error: uncaughtException: JoiObj.string(...).objectId is not a function TypeE ...

Creating an interactive element in Angular: A step-by-step guide

Hey there, I'm facing a problem with creating a specific payload structure as shown in the example code snippet below. Everything was going well until I got stuck at the dynamic form part, and despite several attempts, I can't seem to figure it o ...

Set the text field to be editable or readonly based on certain conditions

Is there a way to conditionally enable or disable an editable field (edit/read only)? I have tried using session role from the database to set conditions on the text field, but I am unsure of how to proceed... <?php include('session.php'); ?& ...

Choose a country from a modal in a React application

click here for image description I need help implementing the screenshot above. My goal is to change the default country name and flag when a user clicks on the country dropdown menu. I have been using headless UI so far, but I'm struggling to figure ...

Guide on expanding the capabilities of IterableIterator in TypeScript

I am currently working on extending the functionality of Iterable by adding a where method, similar to C#'s Enumerable.where(). While it is straightforward to extend the Array prototype, I am encountering difficulties in figuring out how to extend an ...

validation using ajax and php

One question I have is, when I include document.getElementById('myPassword').value); in the validarDados function, it corresponds to valor. Then I need another variable, but valor1 isn't working as expected. The result of echoing $valor1; is ...

Seeking the method to obtain the response URL using XMLHttpRequest?

I'm having trouble with a page (url) that I request via XMLHttpRequest. Instead of getting a response from the requested url, the request is being directed to another page. requesting --- > page.php getting response from > directedpage.php ...