Tips on how to utilize AngularJS formly to reference a form field

I rely on Formly for building my forms using angularJS

Here is an example of one of my form fields:

$scope.postFields = [
    {
        key: 'title',
        type: 'input',
        templateOptions: {
            label: "Title",
            // required: true,
            minlength: 2,
        },
        validation: {
            messages: {
                required: function(viewValue, modelValue, scope) {
                    return scope.to.label + ' is required'
                }
            }
        }
    }
]

I am attempting to interact with my fields in the following manner:

function failure(response) {
    console.log("failure", response)

    _.each(response.data, function(errors, key) {
        _.each(errors, function(e) {
            $scope.form[key].$dirty = true;
            $scope.form[key].$setValidity(e, false);
        });
    });
}

This is how I have structured my formly form:

<formly-form form="postForm" model="model" fields="postFields" class="col-md-4">
    <button type="submit" class="btn btn-primary" ng-click="addPost()">Submit</button>
</formly-form>

I'm encountering an error which states:

TypeError: Cannot read property 'title' of undefined

The issue seems to be on this line of code:

$scope.form[key].$dirty = true;

Is there a proper way to reference created formly fields that anyone can advise on?

Answer №1

If you're looking to easily access the fields within a form, consider adding a name attribute to your fields. By default, Angular-formly generates a name for you which is convenient. However, if you prefer to reference it using a specific key, it's advisable to provide one yourself.

You can achieve this by:

$scope.postFields = [
    {
        key: 'title',
        name: 'title',
        type: 'input',
        templateOptions: {
            label: "Title",
            // required: true,
            minlength: 2,
        },
        validation: {
            messages: {
                required: function(viewValue, modelValue, scope) {
                    return scope.to.label + ' is required'
                }
            }
        }
    }
]

Alternatively, you could automate this process by creating a fieldTransform. Another approach would be to retrieve the NgModelController from the field's formControl property in your error handler like so:

function handleError(fields, response) {
  _.each(fields, function(field) {
    if (response.data[field.key]) {
      field.formControl.$setDirty()
      _.each(response.data[field.key], function(e) {
        field.formControl.$setValidity(e, false)
      })
    }
  })
}

These approaches should help streamline your workflow. Best of luck!

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

React JavaScript application encountered an error: Uncaught SyntaxError due to an unexpected token '<'

My program encountered a syntax error at line <div>Hello World!</div> This is the code that is causing the error <!DOCTYPE html> <html> <head> <script src="libs/react.min.js"></script> <script src="lib ...

update the angularJS selected value to true

When I click on the current Inventory, I want to change my API's selected: true. Can I achieve this with the following code? app.controller('InventoryDetailCtrl', function($scope, Inventory, Assigned, Tags, Restangular, currentInventory) { ...

Tips for filling in the values for the options in a select dropdown menu

Currently, I am facing a strange bug related to the select element. Whenever I open the dropdown, there is always a mysterious black option at the top. This is how my HTML looks like: This particular element is part of my test controller. <select ng- ...

What determines the priority of execution in the execution context stack?

Check out this insightful tutorial on execution context in JavaScript here. It's interesting how the order of invoking functionA() and console.log("GlobalContext") differs in terms of writing code versus the execution context stack. I'm curious, ...

"Flashes of canvas in constant motion between animated scenes

I have a practical exercise to do for school, but I am very new to HTML/JS. The issue I am facing is that my canvas is flashing, like it erases one image and then quickly displays another. I want both images to be displayed at the same time. Here is the co ...

Tips for simulating mouse events in Jasmine tests for Angular 2 or 4

New to Jasmine testing, I'm exploring how to test a directive that handles mouse events such as mouse down, up, and move. My main query is regarding passing mouse coordinates from the Jasmine spec to my directive in order to simulate the mouse events ...

``In a jade view, navigating through JavaScript object properties leads to the addition of quotation marks around strings

Utilizing the npm module traverse to filter data from mongodb / mongoose has been quite helpful for me. Here is an example of the kind of data I might receive: [ { rating: 5, title: { da: 'Web udvikling', en: 'Web Development' } } ...

Is it possible to avoid sending multiple $http requests in Angular? Are there more efficient methods available?

I have developed a rather intricate method for retrieving resources using $http. This method returns a promise and first checks my local cache to see if the resources are already available. If they are, it will return the cached data; if not, it will make ...

The error message in React Hook Form states that the handleSubmit function is not recognized

I'm facing an issue with using react-hook-form for capturing user input. React keeps throwing an error that says "handleSubmit is not a function". Any suggestions on how to resolve this would be highly appreciated. Here's the code snippet I&apos ...

Utilizing AngularJS uib-typeahead to display a customized viewvalue separate from ng-model

I'm working with a uib-typeahead input field. In order to populate it, I need to make an asynchronous call. I want to set ng-model to "CODIGO", but have the viewvalue display as "DESCRICAO". The issue I'm facing is that after selecting an item, ...

What is the best way to incorporate variables into strings using JavaScript?

Can someone help me achieve the following task: var positionX = 400px; $(".element").css("transform", "translate(0, positionX)"); Your assistance is greatly appreciated! ...

Tips for incorporating a QML file into a SwipeView

I attempted to implement swipe view functionality where I needed to load different qml files onto each swipe. In total, I required 7 qml files for 7 swipes and had to include a global property in each swipe. Although I tried using Loader to fetch the qml ...

How can users change the displayed Twitch channel?

My coding skills aren't the greatest, especially when it comes to something like this. I've tried searching for a solution with no luck, so I apologize if this is too basic or impossible. I have a simple page that loads up Twitch with a predefin ...

I am struggling to get the buttons to function properly

I'm working on creating a page with 2 questions and yes/no buttons using jQuery. I've implemented jQuery fade in/out effects for this purpose. However, the buttons don't seem to be functioning as expected. Could someone lend me a hand here?? ...

After resizing, reordering, hiding, or showing columns in the kendo grid, the grid's data source will be set to

I am encountering an issue with my kendo grid where the data disappears after performing certain actions: Reordering columns using mouse drag and drop Resizing columns using mouse drag and drop Hiding columns through the column menu Showing columns throu ...

What methods can be used to indicate the source of a GET request in a protocol?

When I request "/home" and specify that home.html should be served, I want to define the location from which all the resources included in home.html should be retrieved. For instance, if my file system looks like this: -public -home.html -home ...

The closure in question received an undefined Angular parameter

Here is something similar to what I have: $scope.fetchData = function(path, save_to) { $http({method: 'GET', url: 'http://localhost:8001/www-root/' + path}). success(function(data, status, headers, config) { ...

When running the "react-scripts build" command and then serving it, the HTML files are being served instead

After successfully generating the build folder using react-scripts and running npm run build, I attempted to serve it locally with the npm package called serve by running serve -s build. The serve command started running on port 5000 without any issues. ...

ReactJs: Tweaking Padding in Material-UI Table

After inheriting this fullstack app, I noticed that the original developers had incorporated a component to generate tables for the webpage. However, there is an issue with the padding on all the cells being too large. Through Chrome developer tools, I di ...

What changes occurred to module file names following the process of minification?

I'm currently troubleshooting an issue with this particular code snippet: import globalComponents from './global-components'; // ... globalComponents.forEach((component) => { // eslint-disable-next-line no-underscore-da ...