Utilizing a string as a variable in AngularJS: a step-by-step guide

Can anyone help me figure out how to utilize a string as a variable within the scope in my code? Here's what I have:

In my HTML (where type1 can be type2, type3, and more):

<div style="color:red;font-size:11px;">{{ error.type1 }}</div>

And here is part of my controller:

$scope.validate = function(string, value){
        // let's say string = type1
        if (value != 'answer'){
            $scope.error.string = 'Incorrect, try again';
        }
    }

My question is, how do I dynamically set $scope.error.type1 = 'Incorrect'? I have multiple errors displayed on a form above each input field, and the validate function checks when a value is entered. I want to avoid writing numerous conditionals based on the string value. Any suggestions on how to achieve this dynamically?

Answer №1

Could it be possible to implement a reusable directive in this scenario?

<input type='email' ng-model='user.email' />
<error-feedback field='email' errors='errors'></error-feedback>

<input type='text' ng-model='user.name' />
<error-feedback field='name' errors='errors'></error-feedback>

the controller

$scope.errors={}
if (!isValid(user.email)) {
   setError('email','Your email is not valid');
}

if (alreadyExists(user.email)) {
   setError('email','This email already exists');
}

const setError = function(type, error) {
   if ($scope.errors[type]) $scope.errors[type].push(error);
  else $scope.errors[type] = [error];
}

the directive

app.directive('errorFeedback', ['$compile', '$templateCache',
         function($compile, $templateCache) {
             return {
                 template: "<div ng-repeat='error in myerrors' class='error'>{{error}}</div>",
                 scope: {
                     field: "=",
                     errors: "="
                 },
                 controller: ["$scope", "$timeout",
                     function($scope, $timeout) {
                            // assuming errors might be an array
                            $scope.myerrors = $scope.errors[$scope.field]
                     }
                 ],
                 link: function(scope, element, attr) {}
             }
         }
     ])

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 input field values in JS/Ajax without needing to refresh the page or click a button

Currently, I have set up a JavaScript function that submits data without refreshing the page or requiring a button click. The input field is located within tab #2 and triggers the JS function when the user stops typing. However, the issue arises when the ...

Navigating through root and sub applications within AngularJS can be managed effectively when housed in sub directories

I currently have two AngularJS applications in place: The first application serves as the base and operates at the root / The second application is a sub-application that needs to be isolated for design purposes, running within a subfolder such as /foo/ ...

How can I change an element using jQuery's getElementById method?

My current setup involves using a web page as a server and an Arduino as a client. Whenever a specific mode is active, the Arduino sends the following code: <LED>on</LED> The server then adjusts its status accordingly based on this input. I ...

Compiling models at the second level

I am working with a model that looks like this: { content: "Hello world, this is a sample content", notes: { content: "side note, some text here.", index: 2 } } My goal is to convert the model into the following HTML format: <div class= ...

Changing the backdrop hue behind the dropdown menu items to give a fresh look

Objective I aim to change the background color and restrict scrolling when a dropdown is opened. It should have a distinct color from the header, disabling scrolling until the dropdown is closed. Challenges Faced and Solution Attempted To prevent scroll ...

Issues with React Material UI Dialog Displaying Incorrect Information

As I experiment with React Material UI dialog boxes, I've encountered an issue that has me puzzled. I have an object 'a', and when I click on a button in a list, it should display the respective ID number. However, instead of showing the cor ...

The value of innerHTML is currently "undefined"

I am facing a new challenge while working with PHP. I need to edit the content of a div using the product ID fetched from the database. I am trying to accomplish this by iterating through two foreach loops to get the correct IDs separately. The goal is to ...

The XML format is not being rendered properly

Every time I try to access , I receive the following error message: This XML file does not seem to have any associated style information. The structure of the document is displayed below. <rss xmlns:media="http://search.yahoo.com/mrss/" version="2.0 ...

Techniques on how to activate checkbox modification through card clicks

Is it possible to toggle the checkbox value by clicking on a card? <input id="{{a.switchID}}" name="value1" style="display:none;" type="checkbox" ng-click="send(a.deviceID,a.pinNumber,a.switchID,value1)" ng-model="value1" ng-true-value="1" ng-false-v ...

Which property is best suited for styling a phone number field in the MUI data grid in ReactJS?

I previously utilized the pattern attribute for input fields in pure HTML, but now I no longer have any input fields. What should be my next steps? Can you provide me with a reference in the MUI documentation? https://i.stack.imgur.com/ ...

Enclosing sets of lists with div containers

My Objective: <ul> <li class="group4"> <ul class="group2"> <li class="first">stuff</li> <li class="last">stuff</li> </ul> <ul class="group2"> ...

Working with nested SQL queries within a function in a Node.js environment

Hello, I am a beginner in JavaScript. I have a function that might require multiple requests to gather the final data. Can someone guide me on the correct approach to handle this? The issue I am facing is that participants are not being added to the dial ...

AngularJS textbox validation for numbers and required in repeating mode ensures that the user input is a

For more information, please visit the following link: https://plnkr.co/edit/9HbLMBUw0Q6mj7oyCahP?p=preview var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.NDCarray = [{val: '' ...

A custom script for Google Sheets that accesses data from cell "A" and populates cell "B" with information based on the value in cell "A"

Hey everyone, I'm looking to create a script for Google Sheets that will check if there is a value in a cell within a row, and then populate another cell in the same row with a specific value. For instance, if a cell in row 2, column G contains anyth ...

How to Create an Interactive JavaScript Drop Down List for Displaying and Concealing Divs

Looking for some assistance in combining a chained drop-down list with the functionality to show/hide a specific div based on selection. I've come across solutions for each separately, but struggling to merge the JavaScript code (not my strong suit as ...

Extracting the name of a track from the /r/listenToThis subreddit for an IFTTT automation script

I have a list of songs gathered from this subreddit, presented in the following format: [ "Lophelia -- MYTCH [Acoustic Prog-Rock/Jazz] (2019)", "Julia Jacklin - Pressure to Party [Rock] (2019)", "The Homeless Gospel Choir - I'm Going Home [Folk ...

JavaScript has received an event on Server XHR

Situation: There is a scenario where the target API is external and cannot be altered. A JS client initiates sending data to the API upon clicking a button. The code snippet resembles something like this: $.ajax({ type: "POST", url: &quo ...

Three.js displaying only a fraction of gltf model on screen

I've been experimenting with adding this gltf model () using threeJS. The current code snippet is the only approach that has shown me a glimpse of the object, albeit just a small part. If anyone has insights on what modifications are needed, any assis ...

Leveraging data schemas to manage the feedback from APIs

I am curious about the benefits of modeling the API response on the client side. Specifically: First scenario: const [formData, setFormData] = useState(null); ... useEffect(() => { const callback = async () => { try { const fetchDa ...

Tips on transferring information from JavaScript to JSON structures

I'm currently developing a plugin for a static website that functions as a social link locker. I am encountering some difficulties trying to pass data from JavaScript to my JSON. The code snippet is provided below. The issue I'm facing involves ...