Controller unable to access form inside ng-repeat loop in AngularJS

Looking to access a form object within my controller. The form is located inside an ng-repeat block with a dynamic name, and I should be able to access it since version 1.3.

JavaScript:

var app = angular.module('app', []);
app.controller('AppCtrl', ['$scope', function($scope) {
  $scope.forms = [0];
  $scope.testForm = function() {
    if($scope.form0 == undefined) {
      $scope.test = 'Form is NOT defined';
    } else {
      $scope.test = 'Form is defined';
    }
  }
}])

HTML:

<body ng-app="app">
  <div ng-controller="AppCtrl">
    <div ng-repeat="form in forms" ng-init="formName = 'form' + $index">
      form name should be {{formName}}
      <form name="{{formName}}">
        <input type="text" name="field" />
      </form>
    </div>
  <button ng-click="testForm()">Check if form exists</button>
  <p ng-bind="test"></p>
  </div>
</body>

However, in my controller, $scope.form0 remains undefined - after clicking "Check if form exists", I continue to receive the message "Form is NOT defined". Even when I manually assign a static name (<form name="form0">), it still returns undefined. Removing the form from the ng-repeat loop allows it to work properly.

Any insights into why this is happening?

See the example here: https://plnkr.co/edit/Fvy5LdIO0H1vCS9wYR0U?p=preview

Thank you!

Answer №1

The reason for this issue is that ng-repeat generates isolated child scopes, causing the form0 to be located in a child scope and therefore not accessible from the parent scope (the controller's scope).

In order to resolve this, it is necessary to pass the form to the parent scope. However, using ng-init is not an option as the form controller may not be initialized at that point.

One potential solution is to create a custom directive that binds the formController to a specified scope.

app.directive("form",function($parse){
  return{
    restrict:"E",
    priority:-1,
    link:function(scope,ele,attrs){
      var targetScope = $parse(attrs.bindToScope)(scope);
      if(targetScope){
        targetScope[attrs.name] = scope[attrs.name];
      }
    }
  }
})

With this approach, we can instruct the form to bind the controller to the specified scope.

<form name="{{formName}}" bind-to-scope='$parent' >
     <input type="text" name="field" />
</form>

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

Assign values to variables in a JavaScript file using node.js

My tech stack includes node.js, express.js, and either pug or jade. Within my server, I inject a variable called pageId into a view. In the pug view, I utilize this variable using the following script: script. document.addEventListener('DOMConten ...

How can we add up the sum with just one click and then display the

Is there a way to calculate numbers within specific DIV boxes and display the total in a separate DIV when a box is clicked? I've attempted different methods, including enclosing the code within the window.onclick function. Check out my code on this J ...

jQuery UI dynamically adjusting content layout based on browser size changes

Having an issue with my custom accordion script where resizing the browser causes formatting problems in one of the sections. I want the content to remain intact and to utilize a scrollbar if necessary to view the content. The problem is visible in section ...

I am struggling to add a list from these nested functions in Express, but for some reason, the items are not being properly

I am currently working with three nested functions and facing an issue where the last function is not returning the desired list of items. Interestingly, when I log the results of the last function within the loop, I can see the URLs that I need. However, ...

Concealing Website Elements with javascript based on class assignments

Despite my hesitation, I have to ask this question after unsuccessful searches in related articles. In my code, I have 7 nav links all with the same class. Due to the length of the HTML, I am looking for a way to hide contents until the link is clicked, an ...

Using multiple conditions in an angular ngif statement to create a variable

Is it possible to assign the result of a function to a variable in Angular (13) within the .html section of a component, specifically with multiple conditions in ngIf? <div *ngIf="let getMyVar() as myVar && isVisible && isClean" ...

Transforming the API response

After making an Ajax call, the response received is: console.log(data); {"valid":true,"when":"Today"} Attempting to read the response like this: var res = data.valid; console.log(res); results in 'undefined' being displayed. To address this i ...

A guide to implementing Vuex in a Laravel and Vue 3 project

Currently, I am working on a Laravel + Vue 3 project and need to incorporate Vuex into the project. In my store.js file, I have configured my Vuex as shown below: import { createApp } from 'vue' import { createStore } from 'vuex' const ...

Activate the jQuery function multiple times

I am currently working on the menu structure for my website <div class="header"> <ul> <li id="menu__lnk_one"><a href="#">Home</a></li> <li><a href="#">Our Story</a></ ...

Using single quotation marks in Javascript

When the variable basis contains a single quotation mark, such as in "Father's Day", I encounter an issue where the tag is prematurely closed upon encountering the single quotation mark. 'success' : function(data) { div.innerHTML = &apo ...

Discovering the method to retrieve the values from 2 dropdown lists that are populated by a JavaScript function

I have a pair of dropdown lists in a JSP file labeled 'speciality' and 'super_speciality'. Clicking on an option in the 'speciality' dropdown list dynamically populates options in the 'super_speciality' dropdown list ...

What is the process for retrieving a value from JSON utilizing JavaScript?

Unfortunately, I am completely stumped when it comes to Javascript. I'm attempting a few solutions based on online resources. If anyone could offer some assistance, that would be greatly appreciated. Below is the JSON data provided. It has been conde ...

Tips for enhancing the color saturations of cells that overlap in an HTML table

My goal is to enhance the color of overlapping cells in my HTML tables. For instance, when I click on cell 2, the .nextAll(':lt(5)') method will change the class of the next 4 cells. https://i.stack.imgur.com/mwv8x.png Next, clicking on cell 3 ...

Tips for accessing a value from a setInterval function

Is it possible to retrieve a value from the setinterval function in JavaScript? $.ajax({ type : "POST", url:"<?php echo TESTMINE_APP_URL; ?>/ajax/export-details", data:'paginationHash='+paginationHash+'&exp ...

Using Vue.js to iterate through a nested array from an object key

This is a complex v-for loop nested inside another v-for. It displays a list of questions along with the corresponding answers for each question. The key for the question will be used as the key for grouped_answers. The structure of the v-for loop is show ...

Navigate back to the previous page without reloading

Initially, I must clarify that the title of my query may not be entirely representative of what I wish to convey. The situation at hand is as follows: I have developed a jQuery table designed for exhibiting video records. Embedded within this table is a hy ...

Encountering App Crashes during contact.save() operation with ID in Apache Cordova

I have attempted this process with various APIs and even on a physical android device, but it still crashes when trying to save. While developing an app based on contacts for android using Tools for Apache Cordova in Visual Studio and the cordova contacts ...

Displaying Various Items Based on the Language Selected in the Google Translate Widget

Currently, I am in the process of developing a website complete with a shopping cart that will feature different products based on the country of the customer. The client has requested the use of Google Translate to allow for language changes. To accommod ...

When attempting to add a new element to an array, the JSON key is mistakenly assigned a number instead of an array

I'm having trouble creating a JSON object that should look like this: { "sreddy-vm-1":["MyDatabase-1"], "sreddy-vm-2":["MyDatabase-2"], "sreddy-vm-3":["MyDatabase-3", "MyDatabase-4", "MyDatabase-5"] } However, the output I'm getting is diff ...

Using JavaScript to assign multiple classes to a function at separate intervals

I'm trying to add two classes to a JavaScript function, but I'm encountering some issues. When I try to add both classes in the same line, only one of them works. However, if I add each class on separate lines within the function, only the second ...