Encountering an 'undefined' property error when clicking a button in Angular 1.x

Hey there, I have a question that might seem simple to some of you. I'm struggling with fixing an error and I don't quite understand why it's happening :(

This error popped up while using Angular 1.x. What I need help with is creating an alert when the user clicks a button without entering a title in the form.

Let me share my code here, keeping it simple and easy to follow :D

index.html

<div class="form-group">
    <label for="">Title</label>
    <input type="text" ng-model="shipment_template.title" class="form-control">
</div>

<button ng-click="check">Check This</button>

Here's how I handled it in my controller:

shipmentTemplate.controller.js

if (typeof $scope.shipment_template.title == 'undefined') {

    console.log("success")
} else {

    alert("Please fill the title")
}

The issue arises when I enter something in the input field, I see success in the console. However, if I leave it empty, I encounter this error instead.

Cannot read property 'title' of undefined

I initially tried using the length property instead of typeof, but unfortunately, it led to the same error :(

Apologies for any language errors in my explanation, and I would greatly appreciate your assistance in resolving this matter. Thanks! :-D

Answer №1

To solve the issue, simply pass the model into your check function like this:

Here is the HTML code:

<div class="form-group">
 <label for="">Title</label>
 <input type="text" ng-model="shipment_template.title" class="form-control">
</div>

<button ng-click="check(shipment_template.title)">Check This</button>

And here is the JavaScript code:

  $scope.check = function(input) {
    if (input) {
      console.log("success");
    }
    else {
      alert("Please fill the title");
    }
  }

This approach provides a clearer way to achieve your desired result. You can view the working code by visiting: Plunkr

Answer №2

To initialize the delivery_template in your controller, you can follow this code example:

deliveryTemplate.controller.js

$scope.delivery_template = {'name':''};

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

Managing multiple URLs in a MEAN Stack application

Currently, I'm working on a MEAN stack project to implement a CRUD system for managing courses. One specific aspect that is giving me trouble is figuring out how to handle unique URLs for each course I create. As of now, I am using routeprovider for t ...

Angular's ngRoute is causing a redirect to a malformed URL

Currently, I am in the process of developing a single-page application using AngularJS along with NodeJS and Express to serve as both the API and web server. While testing locally, everything was working perfectly fine. However, after cloning the repositor ...

Avoiding the capturing of events on $( document ).mousemove

Each time the browser detects a $( document ).mousemove event, my function is invoked. The performance is smooth with an empty page, but once I introduce a div element and hover over it, the function gets executed twice: first on the document and then agai ...

The Facebook Comments feature on my React/Node.js app is only visible after the page is refreshed

I am struggling with getting the Facebook Comment widget to display in real-time on my React application. Currently, it only shows up when the page is refreshed, which is not ideal for user engagement. Is there a way to make it work through server-side r ...

Validating image dimensions with the data-parsley plugin

Is there a way to validate image dimensions with data-parsley? I attempted the code below, but it is not working. data-parsley-dimensions-options='{ "min_width": "100", "max_width": "100", "m ...

Regular expression: match all content up to a certain word(s)

I have two different versions of a string that look like this: The Student's Companion *Author: Alcock, Pete;May, Margaret;Wright, Sharon*MIL EAN/ISBN: 9781283333115 Java Programming: Java Expert*Author:Sarang, Poornachandra*MIL EAN/ISBN: 978128011 ...

Is there a way to prevent the DOM from loading images until Angular has successfully injected the correct variables?

Having some trouble with this block of code I have: <div class="image" ng-repeat="image in images"> <img src="{{image.url}}"></img> </div> It seems that the image sources are being set correctly, but I keep getting an error wh ...

Transform the styles from a React component into Cascading Style Sheets

I have been tasked with transitioning all the styles from the JavaScript file to the CSS file while ensuring the design remains intact. I am facing an issue where using the CSS styles breaks the search field design. The original design can be seen here: S ...

Here is a way to trigger a function when a select option is changed, passing the selected option as a parameter to the function

Is there a way to call a function with specific parameters when the value of a select element changes in Angular? <div class="col-sm-6 col-md-4"> <label class="mobileNumberLabel " for="mobilrNumber">Select Service</label> <div cla ...

Developing a HTML button through Javascript that triggers a method with a single parameter when clicked

My current project involves creating HTML buttons through JavaScript using AJAX. Each time I click one of these buttons, it triggers an AJAX function. If the AJAX request is successful, it retrieves a number that will be utilized in a for loop. As the loop ...

The Appsheet algorithm determined the exact expiration date as 2 days from the specified date

In my Appsheet, I have two columns: Production Date and Expired Date. If the Production Date is 35 months before the Expired Date, how can I create a formula in Appsheet to calculate this? For example, if the Production Date is 01/10/2023, then the Expired ...

Navigation menu with submenus containing buttons

I attempted to incorporate a dropdown into my existing navigation bar, but unfortunately, the dropdown content disappeared after adding the necessary code. I am now at a loss on how to troubleshoot this issue and make the dropdown function properly. Despit ...

Selecting Content Dynamically with jQuery

I have a webpage with multiple dynamic content sections. <div id="content-1"> <div id="subcontent-1"></div> <i id="delete-1"></i> </div> . . . <div id="content-10"> <div id="subcontent-10"></d ...

Utilizing the controller specified in the template that has been included

Within this snippet of code, I am attempting to utilize a controller named FooCtrl that is defined in the included template app/foo.html, using the directive common.script. angular.module('common.script', []).directive('script', func ...

Disabling prefetch in next.config.js: A comprehensive guide on eliminating data prefetching in Next.js

Typically, in many cases, the disabling of prefetching is achieved by specifically setting a link to not preload. An example of this can be seen below: <Link href="/about" prefetch={false}> <a>About us</a> </Link> My go ...

Issue encountered when sending information to asmx web service via ajax and displaying the result on an HTML page with a javascript function

I have developed an ASMX web service that looks like this: [ScriptService] public class CurrencyData : System.Web.Services.WebService { [WebMethod] public string DisplayCurrency(double amount, string sign ,string style) { swi ...

Creating a Node.JS environment with Express and Socket.IO: A beginner's guide

Trying to set up a Node.JS server on port 3800 of my CentOS server and encountering difficulties: var app = require('express')(); var http = require('http').Server(app); app.get('/', function(req, res){ res.send('&l ...

Is there a jQuery function that can produce repeated output and append content with each successive click?

Attempting to implement a dynamic searchbar with various parameters has led me to explore using jQuery to load and clone the searchbar file in order to append it to the body dynamically. I have made several attempts to modify selectors without achieving t ...

I'm experiencing an issue where my JavaScript function is only being triggered

I have a simple wizard sequence that I designed. Upon selecting an option from a dropdown menu on the first page, a new page is loaded using jQuery ajax. However, when clicking back to return to the original page, my modelSelect() function, responsible for ...

Using jQuery's .each() method to iterate over a JSON object may only display the

Running into some trouble with jQuery.each(). I'm pulling JSON data from another PHP file and trying to display a specific key value from it. This is the JavaScript code I have: <div class="row" id="fetchmember"> <script type="text/javasc ...