AngularJS Array Indexing

$scope.ptArray={m1 : $scope.somevalue1, 
                m2 : $scope.somevalue2, 
                m3 : $scope.somevalue3};
$scope.errMsg={m1 : 'msg1',
                 m2 : 'msg2', 
                 m3 : 'msg3'};
if($scope.ptArray.this==""){
            alert($scope.errMsg.this);
            }

'this' is not functioning correctly in this context. Substituting 'this' with m1, m2, or m3 will work, but only for that specific variable. What should be used in place of this?

Answer №1

To achieve this, you can follow these steps:

First, retrieve all the keys that have an empty string value:

var emptyKeys = [];
Object.keys($scope.ptArray).forEach((key) => {if(ptArray[key] == ""){emptyKeys.push(key);}});

Next, display an alert containing the messages for all those keys:

var alertMessage = "";
emptyKeys.forEach((key) => {alertMessage += $scope.errMsg[key] + "\n";});
if(alertMessage.length > 0){
    alert(alertMessage);
}

Alternatively, you can combine these actions within a single loop:

var alertMessage = "";
Object.keys($scope.ptArray).forEach((key) => 
      {
        if(ptArray[key] == ""){
            alertMessage += $scope.errMsg[key] + "\n";
        }
      });
if(alertMessage.length > 0){
    alert(alertMessage);
}

Answer №2

When looking to access the dictionary, you can utilize the following code snippet:

if($scope.ptArray[str]==""){
     alert($scope.errMsg[str]);
}

Here, the variable str holds a String value of 'm1', 'm2', or 'm3'. However, using an array might be a more efficient choice:

if($scope.ptArray[index]==""){
     alert($scope.errMsg[index]);
}

Here, index is an integer value.

The purpose of this is unclear to me.

Answer №3

Give this a shot

$scope.productArray={n1 : $scope.itemOne, 
            n2 : $scope.itemTwo, 
            n3 : $scope.itemThree};
$scope.errorMessage={n1 : 'error1',
             n2 : 'error2', 
             n3 : 'error3'};

Object.keys($scope.productArray).forEach(function(key){
           if($scope.productArray[key]==""){
                console.log($scope.errorMessage[key]);
           }
     });

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

Several conditional statements in JSX

In my JSX Return() code, I am encountering an "If" issue when one of my conditions has 2 different 'onClick' events. There are 2 'a' tags, where one will display button 'X' if a statement is true and the other will display but ...

What is the proper way to invoke a variable-function in Node.js?

I have a function called `findPeopleByName` that queries the database for a specific username, but I'm not sure how to call it in my Node.js code. Here's what I have so far: // Retrieve user_name from POST request. app.post("/api/exercise/new-u ...

Server experiencing slow performance with Node.js formidable file uploads

When sending files as form data along with some fields using an http post request in angular.js and receiving file in app.post in node.js, the performance is inconsistent. While local testing shows a fast upload speed of 500 mb/sec with formidable, on the ...

ChartJS does not function properly when included in a .php file that is loaded using jQuery's .load() method (

I am facing an issue with this plugin not working when I use the jQuery ajax function .load(). Below is the snippet of my PHP code: <script src="../Chart.js"></script> <script type="text/javascript" src="../functions.js"></script> ...

Encountering issues in the terminal during the installation of React Native

When attempting to install React Native using npm install -g expo-cli, I encountered some errors. I received several deprecation warnings for various packages: [email protected]: This package has been deprecated and now only exports makeExecutableSch ...

Tips for Successfully Transmitting Information via Mat-Dialog

Having trouble passing data from a dialog back to the parent component. Specifically, I'm struggling with updating the value of an array in the `afterClosed` function. I've tried using `patchValue` and `setValue`, but it doesn't seem to be w ...

What is preventing the Date Picker in Selenium from accepting attribute values when using JavaScript for the Spice Jet application?

My implementation of JavaScript for the Date picker in Selenium is running successfully, however, the date is not being selected in the date picker. public class SpicJetBooking { static WebDriver driver; public static void main(String[] args) t ...

How to visually represent options without labels using icons in Material UI Autocomplete

My options are structured as follows: const options = ['option1', 'option2']; I am looking to display the options with icons like this: https://i.stack.imgur.com/aubHS.png The current code for rendering options looks like this: ...

AJAX does not execute all inline JavaScript code

I am currently using AJAX to load a fragment of a document. I have successfully loaded 'external' scripts, but I am encountering issues when trying to execute all the JavaScript within <script> tags. Below is an example of the HTML fragmen ...

What is the best way to assign a value to a property in a Controller or Global Variable using jQuery?

On my ASP MVC 5 site, I have a checkbox within the NavBar element. This checkbox's state dictates whether or not the Grid will display Inactive records alongside active ones on each page. In an attempt to have all controllers access the same property ...

TineMCE fails to trigger ajax-loading when accessing a textarea

Utilizing $.ajax() to inject this particular piece of HTML into a div on the webpage. <div class="board-container"> <form method="post" action="functions.php"> <input type="hidden" name="function" value="set_boards"> ...

Need help setting parsed values on jQuery Autocomplete after Keyup event?

I am using the Bing API to retrieve values by accessing this link: When I parse and append the results on keyup, it works fine. However, when I try to set the results on jQuery's autocomplete, it does not display properly. For example, you can view ...

Unable to access Bootstrap dropdown menu after initial ajax form submission

I am encountering an issue with a dropdown menu on my webpage, specifically within the manager.php file. Please excuse any formatting discrepancies as I am using Bootstrap: <!-- Bootstrap --> <script type="text/javascript" src="https://netdna ...

Create individual account pages with specific URLs in Next.js

I'm currently working on developing a website that will feature individual user pages showcasing their posts and additional information. I'm facing some difficulty in figuring out how to generate new links to access these user accounts. For insta ...

Unusual characteristics of decision-making

Here is a snippet of my JavaScript code: function getSelectedText(){ if(window.getSelection){ select = window.getSelection().getRangeAt(0); var st_span = select.startContainer.parentNode.getAttribute("id").split("_") ...

creating circular shapes with canvas functions

Creating a circle in my game seems to be more challenging than I anticipated. While there are numerous tutorials available, none seem to address my specific issue. The problem lies in where and how to draw the circle within my existing code: function start ...

The process of Including Items into an Array of Objects within a Document utilizing Mongoose.js

I've been searching through various resources for a solution to my problem, but haven't been able to find the answer yet. My goal is to add objects to a new (empty) array in my local MongoDB without any duplicates. Additionally, I need to update ...

angular ensuring seamless synchronization of objects across the application

This question pertains to both angular and javascript. In our angular app, we have numerous objects from the backend that need to remain synchronized. I am facing challenges in establishing efficient data bindings to ensure this synchronization throughout ...

Error Encountered - Node.js application experiencing issues in passport login functionality

I'm in the process of developing a login application using nodejs and incorporating passport js for authentication. The app is connected to a local MySql database and utilizes sequelize as its ORM library. Within my user model, I've implemented ...

How can we replicate the 'setTimeout' feature in Node.js without causing any interruption to the event loop?

After extensive research, I have been trying to figure out how to implement non-blocking code in Node.js. However, all the examples I have come across are tied to functions that already have built-in callbacks. Therefore, I attempted to create my own funct ...