How can I pass ng-model in AngularJS input box without altering it?

Trying to add an ng-model value to an array inside an ng-controller using the input box.

It appears that when checking the box, the ng-model property changes:

Encountering a Problem

https://i.sstatic.net/TU0xh.jpg

https://i.sstatic.net/1qqWu.jpg

https://i.sstatic.net/W8WOc.jpg

I want the ng-model property to remain unchanged when the input is checked. Here's my code:

JSON Model

[
 {
    "nomeservizio" : "Frameworks",
    "framewrok":[
        {
            "name":"none",
            "cost": 40
        },
        {
            "name":"bootstrap",
            "cost": 0
        }
    ]
}]

HTML

    <div class="row" ng-repeat="voce in voices.data">
    <h4 style="color:#000;">{{voce.nomeservizio}}</h4>
    <div ng-repeat="cssframework in voce.framewrok">
        <input type="checkbox" ng-model="cssframework.cost"  ng-change="UpdateTotal({{cssframework.cost}})"/>  
        <span>{{cssframework.name}}........<b>{{cssframework.cost | currency}}</b></span>
    </div>  
</div>

<div class="row">
    <h3>TOTAL: {{selectedVoices}}</h3>
</div>

JS Within Controller

    $scope.UpdateTotal = function(parameter) {
    $scope.selectedVoices = [];
    $scope.selectedVoices.push(parameter);
}   

Answer №1

This solution offers the following benefits:

  • It allows for multiple values from checkboxes and inputs to be stored in an array.
  • Values are saved to the $scope.selectedVoices as an array when the input is clicked.

Whatever your reasons for needing this logic, this solution covers all the features you mentioned.

    myApp = angular.module('myApp', []);
    
    myApp.controller('testController', function ($scope) {

        $scope.selectedVoices = [];
        
        $scope.framework = [{
            "name": "nessuno",
            "costo": 40
        }, {
            "name": "bootstrap",
            "costo": 0
        }, {
            "name": "bootstrap",
            "costo": 20
        }];

        $scope.click = function (key) {
            $scope.selectedVoices.push($scope.framework[key].costo);
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="testController">
    <div ng-repeat="(key, item) in framework">
        <input type="checkbox" ng-click="click(key)" />
        <span>{{item.name}} {{item.costo | currency}}</b></span>
    </div>
    <h1> {{ selectedVoices }}</h1>
</div>

Answer №2

It is important that the model names for values and checkboxes are not identical.

When the checkbox is changed, it updates the model inside the cssframework object as well.

Consider using a structure like this (pay attention to the model in the checkbox input):

<div ng-repeat="cssframework in voce.framewrok">
        <input type="checkbox" ng-model="costo"  ng-change="AggiornaTotale({{cssframework.costo}})"/>  
        <span>{{cssframework.name}}........<b>{{cssframework.costo | currency}}</b></span>
</div>  

In the end, I believe that the ng-model in the checkbox is unnecessary. It is not used in this example.

Answer №3

Essentially, the checkbox functionality in this code snippet sets the ng-model value to true when checked and false when unchecked. Using ng-true-value, you can customize the value assigned when the box is checked, such as setting it to 40. Here's how it works with ng-model:

<div class="row" ng-repeat="voce in voices.data">
    <div ng-repeat="cssframework in voce.framewrok">
        <input type="checkbox" ng-model="cssframework.costo[$index]" ng-true-value="voce"/>  
    </div>  
</div>

This setup allows you to access the values of "cssframework.costo" in the controller using console.log($scope.cssframework.costo), which will return an array.

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

How to Make a Material UI Dialog Box Pop Up in ReactJS to Occupy the Entire Screen

After successfully implementing a Material UI dialog box that pops up when a button is clicked, I now want it to occupy the full screen instead of just a small portion. Despite referring to the Material UI API for guidance on the dialog box settings, I a ...

What is the process of incorporating a video into a react.js project through the use of the HTML

I'm experiencing an issue where my video player loads, but the video itself does not. Can anyone shed light on why this might be happening? class App extends Component { render() { return ( <div className="App& ...

At what point can we rely on the accuracy and timeliness of Element.getBoundingClientRect?

I am currently in the process of developing some code that utilizes Element.getBoundingClientRect (gBCR), combined with inline style updates, to carry out calculations. This particular project is not intended for a general website, so I am not interested i ...

Mall magnitude miscalculation

I am currently experiencing an issue with Galleria and the Flickr plugin. Some images are displaying correctly, while others appear scaled and parts of them are cut off. How can I fix this problem? Below is the HTML code for the Galleria gallery on my web ...

A guide to troubleshooting the error 'response.json is not a function' within an async/await function

Having trouble converting my response to JSON. I keep receiving a TypeError: response.json is not a function error. Can someone please help me figure out what's going wrong? Thanks in advance. componentDidMount(){ this.timingFunction = se ...

Encountering an unanticipated DOMException after transitioning to Angular 13

My Angular project is utilizing Bootstrap 4.6.2. One of the components features a table with ngb-accordion, which was functioning properly until I upgraded the project to Angular 13. Upon accessing the page containing the accordion in Angular 13, I encount ...

Obtain Value from Function Parameter

In my Angular project, I have a function that is called when a button is clicked and it receives a value as an argument. For example: <button (click)="callFoo(bar)">Click Me!</button> The TypeScript code for this function looks like ...

Unidentified Angular JS HTML Functions

Currently, I am developing an application that retrieves data and presents it in a tabular format. To implement sorting and pagination features, Angular JS is being utilized. The pagination section of the app is dynamically added through an Angular functio ...

Controlling the behavior of React components in response to updates

I'm currently learning ReactJs and utilizing the ExtReact framework for my project. I have successfully implemented a grid with pagination, which is functioning well. I customized the spinner that appears during data loading and it works as expected ...

Is there a way to consistently keep the cursor in a single form field using HTML5 and Javascript?

My goal is to ensure that the focus remains on a specific form field at all times. I want this field to be the active one so that any text input goes directly into it. How can I achieve this? I have already tried using the HTML5 autofocus command, but once ...

A proposal for implementing constructor parameter properties in ECMAScript

TypeScript provides a convenient syntax for constructor parameter properties, allowing you to write code like this: constructor(a, public b, private _c) {} This is essentially shorthand for the following code: constructor(a, b, _c) { this.b = b; thi ...

Tips for transferring an AngularJS file using ExpressJS

Being new to ExpressJS, I have a basic example using EJS, but now I am interested in using AngularJS for DOM manipulation. Both technologies provide tools for manipulating the DOM, so why do some people choose to use them together? This is a concept that c ...

Finding an element based on its styling attribute, such as its position on the left or right side

One particular block that caught my eye is the slider element: <div id="sliderDispo" class="slider slider-dispo" data-slider-init="" data-slider-color="#0077b5 #EC6E31 #E40B0B" data-slider-step="33" > <div class="slider__interval" ...

Showing chosen option from dropdown menu

I am having trouble retrieving the selected value from a dropdown menu generated by SQL and sending it back to Flask. I have successfully loaded the dropdown options, but the selected value appears empty when displayed in HTML. Can someone please assist m ...

Adjusting the field of view of a perspective camera in THREE.JS while maintaining the camera's original distance

My ultimate goal is to adjust the FOV value of my camera while triggering an animation. However, upon implementing the FOV value changes, I notice that my scene appears smaller. This has led me to question the mathematical relationship between the FOV val ...

Our express.js does not recognize GET requests from routers

When placeholders and predefined routes coexist in the same location, the predefined routes are never called if the placeholder was declared before them. For example: router.get("/:id", fetchEntry) router.get("/fancy-action/", doSomet ...

Issue with firing Facebook pixel after router.push() in Next.js

Within this code block is FB pixel tracking code <Script id="some-id" strategy="afterInteractive">some fb pixel code</Script> The issue arises when navigating to a page containing the script using router.push(SOME_ROUTE). T ...

Is there a way to integrate my fixed elements with the API call seamlessly?

As a newcomer to web development, I've encountered a hurdle in my current project. I'm working on fetching API images and attempting to attach links to them in my code. However, this process would increase the number of arrays, which poses a chal ...

Vue - Additional loading may be required to manage the output of these loaders

Currently working with Vue and babel. I have a function that's been exported // Inside file a.js export async function get() { ... } I am trying to link this exported function to a static method of MyClass // Inside file b.js import myInterface fr ...

Struggling with implementing Vue.js for making a task list using Bootstrap 5

I'm trying to get the hang of Vue.js. I've been working on setting up a to-do list where users can input tasks, but I'm having trouble getting the list to display correctly when I define the method. It seems like my add() function isn't ...