Assign ng-model dynamically based on user input

I need assistance with creating a group of check-boxes based on an object array. The goal is to have the check-boxes dynamically associate their ng-model with a property of the new object that will eventually be added to the array.

My initial idea was something like this:

<li ng-repeat="item in items">
    <label>{{item.name}}</label>
    <input type="checkbox" ng-model="newObject.{{item.name}}">
</li>

Unfortunately, this approach isn't working as shown in this JSFiddle:

http://jsfiddle.net/GreenGeorge/NKjXB/2/

If anyone has any suggestions or solutions, I would greatly appreciate it.

Answer №2

UPDATE Acknowledging the insightful comments, utilizing this in conjunction with ng-change necessitates a preliminary "dummy" ng-model to already exist. It is worth mentioning that as of version 1.3, the framework seems to have integrated the required options. For more details, refer to this link. /UPDATE

If you find yourself encountering a straightforward scenario amidst a more intricate task, here is the approach I devised for dynamically associating arbitrary expressions with ng-model: this code snippet.

Approach: I formulated a directive named dynamicModel that processes a standard Angular expression, evaluates it, and binds the outcome to the scope using ng-model and $compile.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.data = {};
  $scope.testvalue = 'data.foo';
  $scope.eval = $scope.$eval;
});

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.data = {};
  $scope.testvalue = 'data.foo';
  $scope.eval = $scope.$eval;
});

app.directive('dynamicModel', ['$compile', function ($compile) {
    return {
        'link': function(scope, element, attrs) {
            scope.$watch(attrs.dynamicModel, function(dynamicModel) {
                if (attrs.ngModel == dynamicModel || !dynamicModel) return;

                element.attr('ng-model', dynamicModel);
                if (dynamicModel == '') {
                    element.removeAttr('ng-model');
                }

                // Unbind all previous event handlers, this is 
                // necessary to remove previously linked models.
                element.unbind();
                $compile(element)(scope);
            });
        }
    };
}]);

The usage is quite straightforward: dynamic-model="angularExpression" where angularExpression yields a string utilized as the expression for ng-model.

I trust that sharing this solution might alleviate someone's challenges and prevent unnecessary frustration.

Best regards, Justus

Answer №4

In order to promote more meaningful expression, for example 'model.level1.level2.value', I have devised the following method:

<input class="form-control" ng-model="Utility.safePath(model, item.modelPath).value">

Here, item.modelPath is set to 'level1.level2' and the Utility(model, 'level1.level2') function is utilized to retrieve model.level1.level2

Answer №5

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Angular Form Example</title>
</head>
<body>

    <div ng-app="myApp" ng-controller="myCtrl">
        <form name="priceForm" ng-submit="submitPriceForm()">
            <div ng-repeat="x in [].constructor(9) track by $index">
                <label>
                    Person {{$index+1}} <span class="warning-text">*</span>
                </label>
                <input type="number" class="form-control" name="person{{$index+1}}" ng-model="price['person'+($index+1)]" />

            </div>
            <button>Save</button>
        </form>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {
            $scope.price = [];
            $scope.submitPriceForm = function () {
                //objects be like $scope.price=[{person1:value},{person2:value}....]
                console.log($scope.price);
            }
        });
    </script>
</body>
</html>

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 save multiple instances of a JavaScript function with varying parameters in an array and execute them

I'm looking for a way to efficiently reuse a function multiple times with different ids depending on various conditions, such as select values. Instead of creating a new function for each id, I want a more dynamic approach to handle the potential mult ...

Instructions for creating a po file from a js file using poedit

Utilizing the Gettext.js library for localizing content created from a JS file has been my approach. The current challenge lies in the manual creation and writing of each po file. It is known that php files can be scanned for gettext strings using PoEdit ...

Is there a way to accurately determine the width of a DOM element in a ReactJS application?

While working on a web application using reactjs, I encountered an issue with creating a video player within a specific div container. To address this, I implemented the functionality in the 'componentDidMount' function as shown below: componen ...

Issue with the reload animation jumping too quickly in Framer Motion on NextJS

While creating an animation for my landing page using NextJS with framer motion, I encountered a strange behavior after deploying the site. The animations started to happen too quickly and it felt a bit off. During development on localhost using Chrome, ev ...

Share the beforeAll and afterAll functions from JEST with other developers

In a few of my files, I have this repeated pattern: beforeAll(() => { MockDate.set(1487076708000) }) afterAll(() => { MockDate.reset() }) All I'm doing here is mocking the date. I'm exploring if there's a way to export t ...

Transform jQuery UI Slider input into clickable links

Is there a way to turn the jQuery slider values into clickable links? For example, if the slider is at 1920, can it redirect the user to another page? I've included the code in a fiddle: http://jsfiddle.net/up6Bx/ Any assistance would be greatly app ...

Update the position of a div when an element becomes visible

Currently, I have 3 titles each with a button underneath to reveal more information about the subject. To toggle the visibility of the content, I have implemented a script that shows or hides the corresponding div when the button is clicked. On smaller de ...

Guide to setting up a datePicker in a cellEditorSelector

In my grid, I want to have different editors for different rows within the same column. The ag-Grid documentation provides information on how to achieve this using colDef.cellEditorSelector as a function: link I have successfully created unique editors fo ...

Using document.write within a JSONP callback

My current project involves making a cross domain request using the script tag hack and jsonp. In the callback function, I am attempting to write the received data to the DOM using document.write(). Although I am aware that it is recommended to use append ...

Is there a streamlined approach to signal a successful callback to $q.all without the need to define a $q.defer() variable?

Within my application, I have a mixture of synchronous and asynchronous methods. Here is an example of code from one of the controllers: $q.all([ asyncMethod1(), syncMethod1() ]) .then(function (results) { Even though I don't actually need t ...

Having trouble aligning navigation bar elements accurately in my ReactJS project

I am just getting started with react and I'm in the process of creating my own personal website. The current design of the navbar is shown below. https://i.sstatic.net/2vPhy.png I would like to update it to have a similar appearance to this: https: ...

I am experiencing an issue where my page constantly refreshes even after deleting something

I am attempting to remove an image from both my page and the database without requiring a page reload. HTML <div class ="thumbnail"> <div class="gallery-box" id="Display"> <!-- Thumbnail image --> <?php if (i ...

Tips for removing all elements from an array using jQuery

let values=[]; values.push(data); I have decided to use an array to keep track of my data, and then send it via ajax. The first submission goes smoothly. However, on subsequent submissions, null values are also sent along with the actual data to the serv ...

AngularJS input fields can be formatted to display numbers in a certain

I am facing a challenge with the input field below: <input type="text" class="span2" ng-model="mynumber"> The variable mynumber is initially set to 0.55 from a rest service when the page loads. My problem now is how to format this number for differ ...

Sharing props in React.js among distinct child components using a centralized parent component

I am currently working on developing a front end console using React, which includes a side menu for filtering results from a database and displaying them in a dynamically generated table. The component hierarchy is structured as follows: App.js | |--Sid ...

Launching the Node.js Thread Pool to Enhance Parallel Processing

Hey there! I recently discovered that Node.js operates on a single thread. In order to optimize the performance of my application (MongoDB/Express), I've come up with the following script to utilize all 8 processors: #!/bin/bash node app.js & nod ...

Injecting dependencies through the Angular factory method allows for seamless

I'm in the process of transferring some standard navigation formatting code from the controller to a factory. Should I include $scope in my factory? Despite numerous attempts, I have been unsuccessful in injecting $scope using various methods. Do my ...

Access all querySelectorAll elements individually without the need for looping through the NodeList

Manipulating classes in jQuery can be done with the addClass, removeClass, and toggleClass methods. While similar actions can be taken using native Node methods like classList, a common issue arises when need to perform manipulations on multiple elements ...

Changing the color variable of an object using an onClick function in JavaScript

I'm currently working on a simple game where users can draw using the keys W, A, S, and D. If you want to take a look at the progress I've made so far, here is a JSFiddle link. There's a collision function in the code that I no longer need, ...

What is the best method to eliminate an invalid element from the DOM?

Below is the code snippet showing the xpaths where the value of $value can be found. We have noticed an abnormal tag td1 in the given URL (visible in the image) which is missing a closing tag. It seems like the developers intentionally placed it there, as ...