AngularJS ng-bind not functioning - Unable to assign value to nonexistent property

I'm completely new to AngularJS and I am facing an issue while trying to set a value for a span using AngularJS ng-bind to validate a name input field. Despite my attempts, I haven't been able to make it work.

HTML:

<div class="modal fade" id="myModal" role="dialog"
    aria-labelledby="myModalLabel" aria-hidden="true" ng-controller="modalCtrl as data">

    <input id="name" ng-model="data.name"
       type="text" ng-blur="validateName(this.data)" />
    <span ng-bind="data.name.errMsg"></span>

</div>

JavaScript:

$scope.validateName=function(obj){
    var name = obj.name;
    var regex = new RegExp("^[a-zA-Z0-9\/\@\&\%\*\$\>\<\\[\\]\,\(\)\_\'\;\ \:\\-\\.]+$");
    if(name != undefined && name != null && name.length < 3){
        obj.name.errMsg = "Please enter minimum 3 characters in Name";
        //$scope.name.errMsg = "Please enter minimum 3 characters in Name"
        // TypeError: Cannot set property 'errMsg' of undefined
    }
};

Answer №1

Ensure that the errMsg is defined on the appropriate scope variable.

Here's a suggested approach:

angular.module("app",[])
.controller("modalCtrl",function(){
var ctrl = this;
ctrl.nameObj = {};
ctrl.nameObj.name= "sss";

ctrl.validateName=function(){
    var name = ctrl.nameObj.name;
    var regex = new RegExp("^[a-zA-Z0-9\/\@\&\%\*\$\>\<\\[\\]\,\(\)\_\'\;\ \:\\-\\.]+$");
    if(name != undefined && name != null && name.length < 3){
        ctrl.nameObj.errMsg = "Please enter minimum 3 characters in Name"
        // TypeError: Cannot set property 'errMsg' of undefined
    } else { ctrl.nameObj.errMsg = "";}
};

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="modalCtrl as data">

    <input id="name" ng-model="data.nameObj.name"
       type="text" ng-blur="data.validateName()" />
    <span ng-bind="data.nameObj.errMsg"></span>
    {{data.nameObj.errMsg}}

</div>

Answer №2

The variable obj.name is a string, not an object. It is not possible to set properties on a string type variable. To set the obj variable correctly, you can do so by using the following syntax:

obj = [{name:'name', errMsg:'error message here'}]

Answer №3

<div class="modal fade" id="myModal" role="dialog"
    aria-labelledby="myModalLabel" aria-hidden="true" ng-controller="modalCtrl as data">

    <input id="name" ng-model="data.name"
       type="text" ng-blur="validateName(this.data)" />
    <span ng-bind="data.errMsg"></span> // Using data.errMsg instead of data.name.errMsg

</div>


$scope.validateName=function(obj){
    var name = obj.name;
    var regex = new RegExp("^[a-zA-Z0-9\/\@\&\%\*\$\>\<\\[\\]\,\(\)\_\'\;\ \:\\-\\.]+$");
    if(name != undefined && name != null && name.length < 3){
        obj.errMsg = "Please enter minimum 3 characters in Name"; 
        // Assigning error message to obj.errMsg instead of obj.name.errMsg
    }
};

Answer №4

If you're looking for a solution, give this code a shot. Also, take a look at this plunker link to see a working example based on the scenario provided.

Template:

<body ng-controller="MainCtrl as data">
    <div class="modal fade" id="myModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <input id="name" ng-model="data.name" type="text" ng-blur="validateName(this.data)" /><br/>
        <span ng-bind="data.errMsg"></span>
    </div>
</body>

Controller:

$scope.validateName=function(obj){
    var name = obj.name;
    var regex = new RegExp("^[a-zA-Z0-9\/\@\&\%\*\$\>\<\\[\\]\,\(\)\_\'\;\ \:\\-\\.]+$");
    if(name != undefined && name != null && name.length < 3){
        obj.errMsg = "Please enter minimum 3 characters in Name";
    } else obj.errMsg = '';
};

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 Book Title using Google Books API and ISBN

As a newcomer to Javascript and React-Native, I am in the process of developing a simple app that scans book barcodes for their ISBN numbers and matches them with their titles. Despite successfully retrieving the ISBN number, I am encountering an issue whe ...

Unclear value of button when being passed

In my Welcome.html file, I am attempting to send the value of a button to a function that simply logs that value. This function is located in a functions class that has been imported into my welcome.ts file. <ion-content padding id="page1"> <h1 ...

creating a countdown timer for the carousel

While experimenting, I decided to create a basic carousel from scratch. Initially, I used onclick="function()" to cycle through the images. Later on, I attempted to replace it with onload="setInterval(function, 4000)", but it seems like something went wron ...

What is the best way to style the current element being targeted in React?

In my React application, I am trying to dynamically adjust the height of a textarea element based on its content. I want to achieve this by utilizing an 'onchange' listener to trigger a resize function. While I have successfully implemented the ...

Tips for extracting and structuring strings from unstructured CSV data using JavaScript?

From a public source, I've extracted a string of allergy data: Cedar 679 gr/m3 High, Grass 20 gr/m3 Medium, Trees 80 gr/m3 Medium, Molds Low. Although the number of items may vary, the standard format for trees and grasses is consistent, with allerge ...

Sharing data between functions in JavaScript allows for more flexible and interdependent code structure

After invoking the Showmenu() JavaScript function from C# and passing a variable to it, there is a need to utilize this variable in another JavaScript function. <script type="text/javascript" > var strmenu; function ShowMenu(strmenu) { alert(str ...

Trigger functions by clicking or bind click events by calling a function?

I need help comparing two similar code snippets: myFunc(); function myFunc() { var e = document.getElementByClassName("link"), i = e.length; while (i--) { e[i].addEventListener("click", function() { //do stuff for each ...

Tips for invoking or triggering the Ajax change function when there is only a single option available

<select class="custom-select custom-select-sm mb-3" required="true" id="sel_block"> <option value="0">Select Block From Here</option> <?php // Fetch Blocks $sql_block = "SELECT * FROM blocks WHER ...

The issue arises when attempting to access the response variable in a successful $http call within

Despite the fact that my backend is functioning properly and I'm receiving the correct response from Postman crafted request https://i.stack.imgur.com/JLIrQ.png I am unable to see the response in my angularJS controller. (I execute this call inside ...

Organize the dataset into groups based on every possible key

Hi there, I'm facing a challenge while developing an application using NestJS/Prisma. The task at hand is to extract unique results from a table in order to display them in a filter on the front-end. Let me give you an overview of my table structure ...

Set YouTube Playlist to start from a random index when embedded

I've been trying to figure out how to set my embedded playlist to start with a random video. Here's what I attempted: <iframe src="https://www.youtube.com/embed/videoseries?list=PLPmj00V6sF0s0k3Homcg1jkP0mLjddPgJ&index=<?php print(ran ...

Guide on hiding a div element when clicked outside of it?

How can I create a dropdown feature in Khan Academy where it disappears when clicked outside but stays visible when clicked inside, using JavaScript/CSS/HTML? The current implementation closes the dropdown even on internal clicks. The code includes an even ...

Is there a way to have my MUI Typography component display a unique image cursor when hovered over?

After some testing, I found that setting the cursor to cursor: pointer works perfectly fine. However, my goal is to use a custom image as a cursor. The image is saved in both my src and public folders, but I seem to be struggling with the syntax when using ...

Adding content to an Element Id using JavaScript can be done by utilizing the .insertAfter or .append methods. Since it involves a script tag, you cannot use the dollar sign

I need to include a script after a specific div in my HTML code. Here is what I currently have: <div id="uno">insert after this</div><br /> <p>this is a paragraph</p><br /> <div>this is a div</div> var mysc ...

Unable to retrieve content using the query.ID in Next.js

I'm trying to figure out what is causing the issue in this code, but I can't seem to resolve it. My goal is to use the query.id inside getInitialProps to fetch some content. The fetching process works fine, but when an error occurs, I receive thi ...

JavaScript utilized to create a fully immersive full-screen webpage

I have been trying to implement a code for creating a full-screen website that works on all browsers. Unfortunately, my current code only seems to be functioning properly on Mozilla browser. When I try to view the site in Chrome and make it full screen, it ...

Alexa Account Linking - Error: Account linking credentials are not valid

I've been working on setting up an Alexa skill with account linking. After obtaining the Linking Authorization Code and exchanging it for an Access Token, I attempted to input all the necessary parameters: code, access token, and skill ID into the Ale ...

Is it possible to utilize JavaScript for rotating and cropping a collection of images before uploading them to the gallery?

Struggling to implement file reader and croppie for local image editing (zoom / rotate / crop) before uploading. Seemingly stuck due to a potential DOM issue with the modal, unable to troubleshoot! FileReader () issues // // //create elements for image, ...

just half of the four $_POST variables are actually assigned

Here is a simple form structure: <table class='table table-striped table-bordered table-hover' id='dataTables-example'> <thead> <tr> <th>1</th> <th>2</th> ...

What sets Fetch Promise apart in terms of delivery success?

Struggling with using strapi in my project, as the fetch function returns a promise instead of JSON data This is my code : const [products, setProducts] = useState([]); useEffect(() => { (async () => { try { l ...