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

The ng-model feature is unable to properly save data within a nested ng-repeat function for a 2-dimensional array

I'm currently working with a nested ng-repeat on a 2d array and have added ng-model to the third ng-repeat. However, I am encountering an issue where my ng-model is not properly storing the data within the object. JavaScript Code emrService .getDat ...

What is the best method to loop through this object with JavaScript?

Suppose I have the following data: let testData = { 'numGroup1': [[(1, 2, 3, 4, 5), (5, 6, 7, 8, 9)]], 'numGroup2': [[(10, 11, 12, 13, 14), (15, 16, 17, 18, 19)]] }; What is the best approach to iterate through this data using Jav ...

Modify the properties of the following bdi element that contains text using JQuery

I am not a tech expert, but I have created a script and am running it on a website using Tampermonkey. Website code:- <div id="__grid1-wrapperfor-__label44" class="sapUiRespGridSpanL1 sapUiRespGridSpanM3 sapUiRespGridSpanS6 sapUiRespGridS ...

Monitoring changes in input can be a crucial step in any data analysis

Is there a way to track changes in input using backbone? How it can be achieved in AngularJs: <div ng-controller="W3"> <input type="text" ng-model="val" > <p>{{val}}</p> </div> I would like the value of the in ...

Error: The function isInitial of chunk cannot be found

Currently, I am attempting to build my program using the following command: "build": "NODE_ENV='production' webpack -p", However, I encountered an error message: node_modules/extract-text-webpack-plugin/index.js:267 var shouldE ...

Utilizing AngularJS HotTowel to trigger a spinner when making AJAX requests

I am attempting to trigger the spinner whenever there is an xhr call within the application. Currently, the spinner only appears when clicking on a menu or navigating to a different page. Index page <aside class="main-sidebar"> <!-- ...

Set up a directory alias for the Grunt connect server

I have a set of folders in my project directory that I would like to make accessible using the Connect framework through a Grunt task. The structure of my folders is as follows... / /src index.jade /styles main.css /dist index.html /docs index.htm ...

Eliminate entry upon checkbox completion from task schedule

Currently working on developing my own to-do list web application. I have set everything up except for one thing. I am trying to figure out how to remove a checkbox from the array when it is checked. Can someone please assist me in achieving this using DOM ...

What does the `Class<Component>` represent in JavaScript?

Apologies for the lackluster title (I struggled to think of a better one). I'm currently analyzing some Vue code, and I stumbled upon this: export function initMixin (Vue: Class<Component>) { // ... } What exactly does Class<Component> ...

Using V-model binding in Vue always resets the content of text inputs

I am facing an issue with a Text Input that is filled based on a string stored in cookies, similar to a Remember me feature. When I bind the value of the input to the cookie using :value, I am unable to type a new value even if there is no cookie being sto ...

Locate an element within an array of strings to refine the contents of a flatlist

Currently, I have a FlatList that I am attempting to filter using multiple inputs from dropdown selectors. Here is the code snippet for my FlatList component: <FlatList style={styles.list} data={data.filter(filteredUsers)} ...

What is the best way to retrieve data input from my select dropdown?

I have a select menu generated from a database and I want to display the value of the selected option in an input field. Currently, my code only shows the value of the first option. How can I modify it to display all selected values? Thank you. <?php ...

Creating a visually stunning image grid akin to the meticulously designed layouts found

Forgive my lack of knowledge, but I'm curious about how to create an image or text grid similar to Tumblr using HTML and CSS. I'm looking to achieve a layout like this: ...

Ensuring accuracy within a personalized directive that is implemented numerous times within a single webpage (AngularJS)

Recently, I designed a unique directive that includes various inputs and dropdowns. To ensure proper binding between the outer and inner scopes for two-way data binding, I implemented an isolate scope. This setup allows me to reuse the directive multiple t ...

Tips for adjusting the order in which styles load in NuxtJS

I need to adjust the loading order of styles in my current project. In my custom stylesheet style.css, I've made some overrides, body { font-family: "Lato", sans-serif; font-size: 14px; font-weight: 400; font-style: normal; ...

Next.js production build encountering an infinite loading error

I have been utilizing the Next.js TypeScript starter from https://github.com/jpedroschmitz/typescript-nextjs-starter for my current project. The issue I am facing is that when I attempt to build the project after creating numerous components and files, it ...

Execute a jQuery function every time the class of the parent container div changes

I am seeking to trigger the function below whenever its containing div parent <div class="section">...</div> transitions to an "active" state, for example: <div class="section active">...</div> $(".skills-grid__col").each(function ...

Is your preference selecting made a breeze by dragging the input field?

Looking to create a form that allows users to indicate their preference between Option A and Option B by dragging a slider. I know there must be a library out there that already does this, but I can't seem to figure out what it's called to searc ...

Click on Angular ng-repeat to dynamically insert data using ng-click

When using $http.get to fetch PHP data in ng-repeat, everything works fine. However, I encounter an issue when attempting to use ng-click to add PHP data from a second page into the ng-repeat, but it is not functioning correctly. Do you have any suggestio ...

Combine an array of objects into a regular object

Imagine having an array structure as shown below: const student = [ { firstName: 'Partho', Lastname: 'Das' }, { firstName: 'Bapon', Lastname: 'Sarkar' } ]; const profile = [ { education: 'SWE', profe ...