The issue with AngularJS ng-model not functioning properly with dynamically generated input fields

I have set up a dynamic templateUrl for form fields and I am attempting to use ng-model within ng-repeat. The parent directives and form field directive are functioning correctly and being generated, but when I try to apply ng-model it does not seem to work - the pre-output never changes. Is there a specific method to implement ng-model in this scenario? It works if I hard-code the form inputs instead. I have been following the example in the AngularJS docs.

Markup surrounding the form fields:

<form role="form" ng-controller="FormController as formCtrl" novalidate>

    <div ng-repeat="field in panel.form_fields">

        <form-field field="field"></form-field>

    </div>

    <fieldset class="form-group clearfix">
        <button type="submit" class="btn btn-primary pull-right">Save Progress</button>
    </fieldset>

    <pre>form   = {{models | json}}</pre>
    <pre>master = {{master | json}}</pre>
</form>

Form field directive:

angular.module('formField.directives', [])

.directive('formField', [ '$http', '$compile', function( $http, $compile ) {

    var getTemplateUrl = function( field ) {

        var type = field.field_type;
        var templateUrl = '';

        switch( type ) {
            case 'textfield':
                templateUrl = 'components/form-field/fields/textfield.html';
                break;
            case 'email':
                templateUrl = 'components/form-field/fields/email.html';
                break;
            // additional cases...
        }

        return templateUrl;
    }

    var linker = function( scope, element ) {

        var templateUrl = getTemplateUrl( scope.field );
        $http.get( templateUrl ).success(function( data ) {
            element.html(data);
            $compile(element.contents())(scope);
        });
    }

    return {
        restrict: 'E',
        replace: true,
        scope: {
            field: '='
        },
        link: linker
    }
}]);

Template used for form field:

<fieldset class="form-group">

    <label for="{{field.field_name}}">{{field.field_label}}</label>
    <input type="text" 
           class="form-control"
           id="{{field.field_id}}"
           name="{{field.field_name}}"
           value="{{field.field_value}}"
           placeholder="{{field.field_prompt}}"
           ng-required="field.field_required"
           ng-disabled="field.field_disabled"
           ng-model="models[field.field_name]">

</fieldset>

Controller from the AngularJS docs example:

.controller('FormController', ['$scope', function( $scope ) {

    $scope.master = {};
    $scope.models = {};

    $scope.update = function( models ) {
        console.info('Update');
        $scope.master = angular.copy( models );
    };

    // additional controller functions...

    $scope.reset();

}]);

Answer №1

The instructions you provided operate on isolated scope (.$new(true)). This means any changes made inside the directive will not be directly reflected in the outer scope unless utilizing 2-way bindings or similar methods. Therefore, the

ng-model="models[field.field_name]"
within your directive does not refer to the same object as the models in the parent controller's scope. To resolve this issue, pass the model using 2-way binding.

When implementing it:

<form-field field="field" model="models[field.field_name]"></form-field>

In your directive template:

<input type="text" 
       class="form-control"
       id="{{field.field_id}}"
       name="{{field.field_name}}"
       value="{{field.field_value}}"
       placeholder="{{field.field_prompt}}"
       ng-required="field.field_required"
       ng-disabled="field.field_disabled"
       ng-model="model">  <!-- Ensure to set the model on the scope for 2-way B -->

In the isolated scope declaration of your directive do:

scope: { field: '=', model: '=' },
//or specify a reference to the object holding models in the field property itself.

Plnkr

Please note that specifying value="{{field.field_value}}" and ng-model in your directive template will not automatically set the default value. You must set the default value within the ngModel itself.

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 navigate users to a different page using AJAX upon receiving a successful response from PHP?

I am currently using a JavaScript function that is functioning correctly. It retrieves all error messages from the PHP file and displays them in a span with the ID "resto" without any issues. However, I now have a requirement where if the PHP file return ...

Error occurs when trying to create or delete a folder in Express.js

Implement Folder Creation Code in index.js let companydir = './views/campaigns/' + companyname; if(!fs.existsSync(companydir, { recursive: true })) { fs.mkdirSync(companydir, { recursive: true }); } var dir = companydir + &apo ...

Utilize jQuery to enclose nested elements within a parent element

There is a Markup presented below, where this HTML content is being generated from Joomla CMS. I am seeking a jQuery method to reorganize this HTML structure without modifying its PHP code. <div class="item column-1"> <div class="page-header"& ...

Enhance Canvas when React State Changes

I am currently working on integrating a canvas into my React project. The main goal is to overlay styled text (with custom font color, style, and size) on an image. I've set up a basic form to input the styling attributes and the desired text. Whenev ...

Looking to retrieve the value of an input element within an ng-select in Angular 6?

Currently, I am working on a project where I aim to develop a customized feature in ng-select. This feature will enable the text entered in ng-select to be appended to the binding item and included as part of the multiselect function. If you want to see a ...

Utilizing Nested Click Events in jQuery to Enhance User Interaction

I'm really struggling with this and can't seem to find a solution anywhere. I want to capture data when button A is clicked, and then submit that data via AJAX when button B is clicked. Here's what I've been considering: $(document).o ...

What could be causing the issue where a POST request from angular.js fails to work, but when sent directly from a form

In my current project, I am implementing basic authentication in node.js with passport.js using the LocalStrategy method. Although password validation has not been incorporated yet, user accounts are being stored in a MongoDB instance. I encountered a maj ...

Issue with Moment.js: inability to append hours and minutes to a designated time

I have a starting time and I need to add an ending time to it. For example: start=19:09 end=00:51 // 0 hours and 51 minutes I want to add the 51 minutes to the 19:09 to make it 20:00. I've attempted several different methods as shown below, but none ...

Updating front end data using Node.js - A Comprehensive Guide

I am looking to create a website using node.js that can dynamically display a plot and update the data every minute without needing to refresh the entire page. As someone new to node.js, I am interested in learning how to use "get" requests to update the d ...

The requested URL socket.io/1/?t= cannot be located

I've created a web application running on rails 4 at localhost:3000. A client-side angularjs is also incorporated into the project. The socket.io.js file has been placed in the public folder of my rails app. In my angularjs client code, I have the fol ...

Automatically change and submit an <input> value using jQuery

I have been working on a prototype to enable users to access all the data associated with a visualization. The idea is that they would click on a specific point, triggering a modal to appear, and within that modal, a table would dynamically filter based on ...

Breaking the condition within the while loop (Now featuring a code snippet)

Let's clarify the condition in the while loop, which should check if the new challenge number has not been completed yet (as indicated in the challenges.finished array). This means that the same challenge can be displayed multiple times instead of jus ...

Invoking PHP function within a specific class using Ajax

I am currently utilizing Zend Framework. My PHP class is structured as follows: FileName : AdminController.php Path : /admin/AdminController.php Ajax Function : function exportToExcel() { $.ajax({ url: "/admin/AdminController/testFunction", ty ...

Access to JSON.stringify is prohibited

I have an array containing objects in JavaScript that I need to save as a .json file. Prior to saving the objects, I displayed them using console.log. // Client Object {id: "1", color: "#00FF00"} Object {id: "2", color: "#FF7645"} Object {id: "3", color: ...

React Native - Implementing a dynamic form that adapts based on the answer given by its parent

My JavaScript Object has a simple state structure as follows: pertanyaan: [{ label: "label1", type: 'dropdown', key: 'keyFoo1', option: [{ value: "foo1" }, { value: "foo2", additional ...

Tips for resolving the [vue/no-use-v-if-with-v-for] warning in Vue

I am encountering an issue with a div element that supports v-for and v-if. The output is correct, however, there is a warning that I find quite annoying: [vue/no-use-v-if-with-v-for] The 'prit_type_ids' variable inside the 'v-for' dir ...

Determine the instance's name as a string in JavaScript

Currently, I am utilizing Three.js in combination with javascript. Upon running the following line of code: console.log(this.scene.children[1]) I receive the following output in the console within Chrome: https://i.stack.imgur.com/6LBPR.png Is there a w ...

The Bootstrap modal is not properly clearing all attribute properties when it is hidden

Alrighty, so I've got this modal set up: <div id="modal-container" class="modal fade" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content center-block" style="displ ...

Unspecified data transfer between child and parent components

I'm working on implementing a file selection feature in my child component, but I'm facing difficulties passing the selected file to the parent component. I'm struggling to find a solution for this issue and would appreciate some guidance. W ...

Dynamic addition of modules to my Angular application is a must

Is there a way to dynamically load modules in my Angular application based on user selection after they have logged in? ...