Ensure that a form field is validated using a dynamically assigned name in Angular

Generating a dynamic form in the view involves iterating through an object containing various user questions. Each question has a unique attribute called formFieldName, which assigns a random string as the field name.

<form name="includedForm.newRequestForm" class="form-horizontal" role="form" novalidate>    

<div ng-if="message.question.attributes.structure.type == 'object'">
    <div ng-repeat="(index,objField) in message.question.attributes.structure.properties">
        <div ng-if="objField.type == 'array'" class="form-group" show-errors>
            <label for="{{objField.formFieldName}}" class="control-label col-sm-6">{{objField.title}}
                <br /><i><small>{{objField.description}}</small></i></label>
            <div class="col-sm-6">
                <select class="form-control" name="{{objField.formFieldName}}" multiple ng-model="objField.userValue" ng-required="objField.required">
                    <option ng-repeat="option in objField.items.enum" value="{{option}}">{{option}}</option>
                </select>
            </div>
        </div>

        <div ng-if="objField.type == 'boolean'" class="form-group" show-errors>
            <label for="{{objField.formFieldName}}" class="control-label col-sm-6">{{objField.title}}</label>
            <div class="col-sm-6">
                <input class="form-control" name="{{objField.formFieldName}}" ng-model="objField.userValue" type="checkbox" ng-value="option" ng-checked="message.question.attributes" />
            </div>
        </div>
    </div>
</div>

<div class="col-sm-12">
    <button ng-click="markAsDone(message)" class="btn btn-primary">Done</button>
</div>
<form>

The controller retrieves the formFieldName attribute successfully, but utilizing it for validation remains a challenge.

var MarkAsDone = function(message) {

    $scope.includedForm = {};
    var formField = message.question.attributes.formFieldName;
    if ($scope.includedForm.newRequestForm.{{formField}}.$valid){
        //submit the form
    }
}

Answer №1

to respond to your inquiry:

  1. Initially, the equivalent of $scope is {{}} so it should only be used in HTML. In your JavaScript, use $scope and in HTML use {{}}, which establishes a pipe (2-way binding), allowing for bidirectional binding between $scope.variable.property and {{variable.property }} in HTML.

    $scope.includeForm.email === {{ includeForm.email }} === ng-model="includeForm.email" === ng-bind="includeForm.email"
    

    If you set any one of these, all will be set. So, if you set $scope, it will reflect in HTML, and as user input is captured, it is already stored in $scope ... all interconnected.

  2. When trying to retrieve the value from HTML back into JavaScript, you need to create and set a $scope variable. For example, if you create $scope.dataModel.dataProperty and use it in ng-model=dataModel.dataProperty, you again have two-way binding. There's no need to do anything extra as Angular manages the data flow. Hence, extracting the value to a variable is unnecessary since $scope.dataModel.dataProperty is already established once the user checks the box.

    var formField = $scope.dataModel.dataProperty;
    // However, as mentioned, there's no need since $scope.dataModel.dataProperty; serves as your variable
    
  3. In JavaScript, when using a dynamic property as an object property key, place the dynamic value inside []. For instance,

    $scope.variable[dynamicProperty].method;
    // You can assign a static property as a key using dot notation, like this:
    $scope.variable.staticProperty = val;
    

I hope this explanation proves useful.

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

What is the best way to transform a string into a sequence of numbers using JavaScript?

Is there a clever method for transforming a string into a sequence of numbers in Javascript (not just converting "0.5" to 0.5, but rather "Hello" into 47392048)? Any suggestions are welcomed. Many thanks! ...

AngularJS component downgraded without change detection

Currently, I am utilizing Angular's downgradeComponent for performance optimization purposes. You can find more information about it here: https://angular.io/api/upgrade/static/downgradeComponent. The Angular component I am working with is defined as ...

Components undergo a style transformation with Material UI

I've noticed that every time I render the component, the styles keep changing. import React from 'react'; import FormControl from '@material-ui/core/FormControl'; import MenuItem from '@material-ui/core/MenuItem'; im ...

Utilizing Node and Express to promptly respond to the user before resuming the program's

I am accustomed to receiving a user's request, handling it, and providing the outcome in response. However, I am faced with an API endpoint that requires about 10 tasks to be completed across various databases, logging, emailing, etc. All of these ta ...

How can I incorporate a custom function in Robo3T?

After installing Robo3T (previously known as robomongo), a GUI for mongo db, I wanted to add a custom function to retrieve the last N documents in normal order. The query statement I used was: db.getCollection('i1801').find().skip(db.getCollecti ...

displaying and concealing elements within a directive based on their attributes using angular

I recently started learning about angular development. I've created a directive that utilizes a featured items template, which will be used in various sections of the page. This template sometimes includes a "view all items" button, and sometimes it ...

Pass a variety of data points to PHP using Ajax requests

I am facing a challenge with passing multiple parameters during Ajax calls. The code works perfectly when I only pass one parameter. Here is the code snippet for the Ajax call: $.ajax({ type: "POST", url: "dataCartas.php", ...

What is the best way to change a variable in an AngularJS view?

My Request In my application, I have implemented 3 views, each with its own controller. The first view is the home screen, and from there the user can navigate to view 2 by clicking on a div element. On view 2, the user can then move to view 3 by clicking ...

What is the most effective way to extract the output from a JSONP request and utilize it beyond the

I have a function that is working well. I had to use JSONP to handle cross-domain issues, and I also wrote an HTTP module to change the content-type. However, I did not include a callback name in the URL. function AddSecurityCode(securityCode, token) { va ...

The Challenge of Upgrading from AngularJS 1 to Angular 2: An Adapter Solution

<html lang="en"> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="app.css" type="text/css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script> <script src="https:/ ...

Enhancing realism with ambient occlusion in three.js

After successfully converting my first cloth simulation from OpenGL to WebGL using three.js, I noticed that it looks a bit dull. I am hoping to add ambient occlusion for nicely shaded effects when the cloth collides with a ball. Unfortunately, my knowledge ...

What is the best method to extract information from JavaScript tables using Python and Selenium?

As a beginner in Python, JavaScript, and Web-Scraping, I am facing the challenge of extracting data from tables on a specific webpage (https://www.mcmaster.com/cam-lock-fittings/material~aluminum/) and saving it into a csv file. https://i.sstatic.net/xQBO ...

Using Laravel to manipulate JSON arrays

In my project with Laravel 5.3 and AngularJS, I send JSON data from AngularJS to the server like this: {"grc":{"id":1},"floatingGrcs":[{"days":"10","units":"100"},{"days":"20","units":"200"}]} Now, I need to extract and work with this array in my Laravel ...

Implementing a feature that loads older posts on a webpage as users scroll down

Spent hours trying to get my site to automatically load older posts on scroll down with no luck. Any assistance is greatly appreciated :) After researching, [this tutorial][1] seemed like the best solution so I followed it step by step and integrated ever ...

Implementing pagination for images offers a user-friendly browsing experience

My friend and I are in the process of creating a website that displays images from two directories in chronological order. The image name serves as a timestamp, and we generate a JSON object using PHP with the code below: <?php $files = array(); $dir ...

Is there a way to retrieve all "a" tags with an "href" attribute that contains the term "youtube"?

My goal is to capture all a tags that have the href attribute containing the word youtube. This task requires the use of jquery. ...

What strategies can be used to maintain version consistency of duplicated dependencies within a Javascript monorepo?

In my Typescript monorepo with Javascript packages, each package has its own package.json file where dependencies are defined. Some external dependencies may be duplicated across multiple packages. repo/ ├── package.json ├── packageA │   ...

Adjust the dimensions of the thead, tbody, and td elements on the fly

I've implemented this property in a .css file on the table shown below and there are 9 records. .fixed tbody td, thead th { width: 5.2%; float: left; } In my scenario, when there are 4 columns, the width should be 23.2%; for 5 columns ...

Tips on preventing the need for a placeholder Vue data structure at the start-up phase

Within my Vue-powered HTML, I came across the line: <span>Last updated on {{incident.LastUpdate[0].date}}</span> In the Vue instance, I have declared the data as: data: { incident: {} } During the execution, the incident is asynchronous ...

What's the best way to assign an array of objects to the state in React?

Currently, I am executing an SQL query in my node/express backend and transferring the result to my React front end via JSON. After checking the information using console.log, everything seems to be working correctly. However, I am encountering difficultie ...