Using AngularJS to bind a dynamically created form built in JavaScript

I am looking to dynamically build a form using JavaScript and utilize it within an AngularJS form controller.
In the example provided below, the form is not rendering as HTML, and I aim to bind it to the model variable. http://jsfiddle.net/g6m09eb7/

<div>
    <form ng-controller="TodoCtrl" ng-submit="blabla()">
        <div ng-repeat="field in fields">{{field.input}}</div>
    </form>
</div>

function TodoCtrl($scope) {
    $scope.model = {
        'FirstName': 'Test',
        'LastName': 'Test Last'
    }
    $scope.fields = [{
        input: '<input type="text" ng-model="model.FirstName">'
    }, {
        input: '<input type="text" ng-model="model.LastName">'
    }, ];
}

Answer №1

In this demonstration, I will outline how to achieve a specific outcome for informational purposes. Please note that the method described here is not recommended for solving your broader issue. Although this example extracts HTML from the document, it does not integrate with Angular. For proper integration, you would need to utilize an alternative directive, such as this one (click). This approach is fundamentally flawed.

angular.module('myApp', [])
.controller('TodoCtrl', function($scope) {
    $scope.fields = [{
        input: '<input type="text" ng-model="model.FirstName">'
    }, {
        input: '<input type="text" ng-model="model.LastName">'
    }, ];
})
// filter to make Angular trust the html
.filter('safeHtml', ['$sce', function ($sce) { 
    return function (text) {
        return $sce.trustAsHtml(text);
    };    
}])
;                     
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app="myApp" ng-controller="TodoCtrl">
   <!-- use ng-bind-html on trusted html to bind it (see the js) -->
  <div ng-repeat="field in fields" ng-bind-html="field.input | safeHtml"></div>
</form>

Alternatively, you can simplify the process by leveraging the object properties directly for the ng-repeat functionality. This results in a more straightforward and efficient solution!

angular.module('myApp', [])
.controller('TodoCtrl', function($scope) {
  $scope.model = {
    'FirstName': 'Test',
    'LastName': 'Test Last'
  };
})
;                     
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app="myApp" ng-controller="TodoCtrl">
  <div ng-repeat="(key,value) in model">
      <input type="text" ng-model="model[key]"/>
  </div>
</form>

It is essential to refrain from mixing controller logic with DOM manipulation. Placing HTML snippets in a controller usually indicates a misguided approach. Directives should handle all DOM manipulations conclusively.

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

The amazing magnific popup boasts a pair of close buttons

I recently started working on integrating a front-end HTML theme with a back-end Laravel app. Oddly enough, I noticed that the popup modal is displaying two close x buttons instead of just one. Despite my efforts, I have been unable to pinpoint what exactl ...

Utilizing ID's within a jade template embedded within a P HTML element

Using the jade template, I successfully formed this paragraph. My next step is to add an ID or a class around the word stackoverflow. How can I achieve this in jade? I am aware that in regular HTML we would use something like <div class="className"> ...

Is there a different method similar to Textfield onChange that works like the HTML onChange attribute?

In my current setup, I have a Textfield component nested within other components where I pass a function pointer down to it as a prop. The challenge I'm facing is that the function responsible for passing the contents of the Textfield back up to the r ...

Utilize Express efficiently by requiring modules only once for multiple routes within the application

Here is an overview of my project directory structure: MyProject -app.js -routes -routeone -routetwo In the app.js file, I have the following setup: var express = require('express'); var app = express(); var routeone = ...

Why is the view not reflecting the updates made to the model?

I recently started delving into Angular JS and have been following tutorials to learn it. One issue I'm facing is that my model doesn't seem to update the view. Can anyone help me figure out why this is happening? Here is the code snippet: < ...

issue with using references to manipulate the DOM of a video element in fullscreen mode

My current objective is to detect when my video tag enters fullscreen mode so I can modify attributes of that specific video ID or reference. Despite trying various methods, I have managed to log the element using my current approach. Earlier attempts with ...

Can Google Charts be integrated with $refs in VueJS?

I'm currently working on implementing a timeline chart with Google Charts. The chart is displayed within its own component, which I later invoke from a higher-level parent component. However, I've run into an issue where the drawChart function re ...

Using blending modes with gradient colors in an SVG design

I'm struggling to get my logo to change colors upon scrolling into a button with similar gradient colors, but I just can't seem to make it work. Can anyone lend me a hand? Thank you! Take a look at my Logo. I've attempted to add some styles ...

What can you tell me about Page Event functionality in Datatables?

Curious question -- I'm currently seeking a practical example of how to implement a 'page' event in a project utilizing DataTables. The provided documentation can be found here -- http://datatables.net/docs/DataTables/1.9.4/#page. Despite t ...

Currency format Material Design Input

Are there any input options within Material Design that support specific formats like currency? If this feature is not available, what alternatives would you recommend to achieve the desired functionality? Appreciate your help. ...

Encounter a critical issue while making a JSON request using Kendo UI

I am facing an issue at my workplace where I need to integrate Angular.js with ASP.NET MVC. Currently, I am trying to build a simple application that features a Kendo UI grid on the front page. In my App.js file, I am fetching data from the Data Controller ...

Tips for assigning unique non-changing keys to siblings in React components

I've been searching for a solution for more than an hour without success. The structure of the data is as follows: const arr = [ { id: 1, title: 'something', tags: ['first', 'second', 'third'] }, { id: 2, t ...

Importing modules using relative paths results in failure due to module not being found, whereas employing absolute paths

I have been encountering this problem for a considerable amount of time and have made multiple attempts to resolve it. I am currently working on the development of my discord.js bot and recently switched from TS back to JS due to certain complications I fa ...

Struggling to get collapsible feature functioning on website

I'm trying to create a collapsible DIV, and I found a solution on Stack Overflow. However, I'm having trouble getting it to work on my website. I created a fiddle with the full code, and it works there. But when I implement it on my site, the con ...

The cdkDropList in Angular's drag and drop feature does not support the application of element styles

Just wanted to share my experience in case it helps someone else out there! I've been working on an Angular project where I needed to create a Trello-like application. To enable dragging elements from one list to another, I installed the Angular cdk ...

Struggling with the integration of a custom login feature using next-auth, leading to being constantly redirected to api/auth/error

Currently, I am facing a challenge while working on my Next.js application. The issue lies with the authentication process which is managed by a separate Node.js API deployed on Heroku. My objective is to utilize NextAuth.js for user session management in ...

Adding style tags dynamically to a component and then encapsulating the styles again (using Angular)

Currently, I am in the process of upgrading from AngularJS to Angular. Our app is currently a hybrid one being bundled up with webpack instead of just angular cli. Due to this setup, we have encountered issues where our css or scss files are not correctly ...

Dealing with errors in node.js

Node.js asynchronous functions typically have a callback, with some like fs.writeFile passing an err argument. fs.writeFile('message.txt', 'Hello Node', function (err) { if (err) throw err; console.log('It\'s saved!& ...

What causes jQuery to not work correctly during keydown events?

I've been working on this external jQuery code: jQuery(document).one('keydown', 'g',function (evt){ if ($("#tb").html() == "0") { $("#tb").html("Testing the chicken.") } else {$("#tb").html("Chickens fart too." ...

Switching between height: 0 and height:auto dynamically with the power of JavaScript and VueJS

Currently, I am changing the height of a container from 0px to auto. Since I do not know the exact final height needed for the container, using max-height could be an option but I prefer this method. The transition from 0 to auto works smoothly, however, ...