Replace the value of a variable when another variable becomes false in Angular.js

Currently, I am working on a project using Angular and have run into an issue that I need help with:

In my project, I have two variables - signed which is a boolean bound to a checkbox, and grade which is an integer bound to a number input field.

I am looking for a way to automatically set signed to true when the value of grade becomes greater than or equal to 2. Additionally, I want grade to automatically change to "1" when signed is set to false. Currently, I am manually calling two functions to achieve this, but I am wondering if there is a more efficient solution.

Any suggestions would be greatly appreciated.

update: I forgot to mention that I have multiple subjects, each with their own signed and grade properties. It is important that changes in one subject's properties do not affect the properties of another subject.

Answer №1

Here's an example using the ng-change directive:

HTML:

<input ng-model="subjects.a.grade" ng-change="changeGrade('a')">
<input ng-model="subjects.a.signed" ng-change="changeSigned('a')">

In your controller :

$scope.subjects = {'a' : {'signed' :false, 'grade' : 1} ,
                  'b' : {'signed' :false, 'grade' : 2} };

$scope.changeGrade = function(s){
    if($scope.subjects[s].grade >=2  ){
        $scope.subjects[s].signed = true ;
    }
}

$scope.changeSigned = function(s){
    if(!$scope.subjects[s].signed){
        $scope.subjects[s].grade = 1 ;
    }
}

Answer №2

Why should you avoid using functions in this way?

<div ng-controller="MyCtrl">

     <input type="checkbox" ng-model="data.signed" ng-change="updateGrade()" />
     <input type="number"   ng-model="data.grade"  ng-change="updateSigned()" />

 </div>

Additionally,

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

function MyCtrl($scope) {

    $scope.data = 
     {
       grade  : 2, 
       signed : false
     }; 

    $scope.updateGrade 
       = function()  {  this.data.grade  = !this.data.signed ?  1 : this.data.grade; }

    $scope.updateSigned 
       = function() {  this.data.signed =  this.data.grade  >= 2  ? true : false;   }

}    

http://jsfiddle.net/k1dbl4ck/HB7LU/21953/

In essence, relying on functions like this may complicate code later when trying to retrieve values from the inputs instead of simply binding them initially and having easy access to the $scope.data model throughout.

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

When React-select is toggled, it displays the keyboard

While using react-select ^1.2.1, I have come across a strange issue. Whenever I toggle the drop-down in mobile view, the keyboard pops up unexpectedly as shown in this screenshot https://i.stack.imgur.com/mkZDZ.png The component code is as follows: rende ...

Javascript callback function cannot access variables from its parent function

As a Javascript newbie, I am currently diving into callbacks for my project. The goal is to retrieve address input from multiple text boxes on the HTML side and then execute core functionalities upon button click. There are N text boxes, each containing an ...

What prevents me from extending an Express Request Type?

My current code looks like this: import { Request, Response, NextFunction } from 'express'; interface IUserRequest extends Request { user: User; } async use(req: IUserRequest, res: Response, next: NextFunction) { const apiKey: string = ...

Looking for a skilled JavaScript expert to help create a script that will automatically redirect the page if the anchor is changed. Any t

Seeking a Javascript expert, In my custom templates, I have used a link as shown below: <a href='http://www.allbloggertricks.com'>Blogging Tips</a> I would like the page to redirect to example.com if the anchor text is changed from ...

Trigger a Vue method using jQuery when a click event occurs

I'm attempting to attach a click event to an existing DOM element. <div class="logMe" data-log-id="{{ data.log }}"></div> ... <div id="events"></div> Struggling to access external Vue methods within my jQuery click handler. A ...

Angular Handsontable experiencing issues when used with standard scope variables

In my Angular application, I have a scope variable named "xd" that I want to display in a table. When using a traditional table structure, everything works perfectly: <table class="table"> <tr ng-repeat="x in xd"> <th ng-bind="x.title ...

Guide to Binding a JSON Property (Set or Array) to an Interactive Input Form in AngularJS

My input form is structured like this: <div> <div class="form-group"> <label for="inputQuestion" class="col-sm-2 control-label">Question</label> <div class="col-sm-10"> <input data-ng-model="publication.qu ...

Tips for showing form values in pop-up boxes based on their unique identifiers

I am experiencing an issue with displaying posted values in a pop-up box. Specifically, when I click on "Book now", it only shows one set of id values for all entries. For example, if I click on the 1st row's "Book now" button, it displays the values ...

Incorporate a new node module into your Ember CLI application

I am interested in integrating the Node.js module https://www.npmjs.com/package/remarkable-regexp into my Ember-CLI project. Can someone guide me on how to make it accessible within the Ember application? I attempted to do so by including the following c ...

Processing data from a Buffer object using the .map() method and sending it as props to a component

As I work on my application, I encounter a challenge when dealing with a Buffer object that contains data from a file. My intention is to render the component Bar for each byte in this buffer and pass the byte as a prop. However, I am facing an issue with ...

The show more/show less link for a long jQuery paragraph is malfunctioning

I encountered an issue while coding where the "read more" link works correctly, but the "show less" link does not. Despite my efforts, I cannot seem to identify the error. Within this code snippet, there is an anchor tag with class="show-less" that I am u ...

Instructions on how to insert a single parenthesis into a string using Angular or another JavaScript function

Currently, I am employing Angular JS to handle the creation of a series of SQL test scripts. A JSON file holds various test scenarios, each scenario encompassing a set of projects to be tested: $scope.tests = [ { "Date": "12/31/2017", "Project": ...

Can anyone provide guidance on how to calculate the total sum of a JavaScript array within an asynchronous function?

Currently, I am working with Angularjs Protractor for end-to-end testing and faced an issue while trying to calculate the sum of values in a column. Although I am able to print out each value within the loop successfully, I am struggling to figure out ho ...

What is the best way to notify my form that a payment has been successfully processed?

I'm working on a form that has multiple fields, including a PayPal digital goods button. Clicking on this button takes the user out of the website's workflow and into a pop-up window for payment processing. Once the payment is completed, the retu ...

The tooltip function is not functioning properly on Internet Explorer when the button is disabled

I have been utilizing a similar solution found at http://jsfiddle.net/cSSUA/209/ to add tooltips to disabled buttons. However, I am encountering an issue specifically in Internet Explorer (IE11). The workaround involves wrapping the button within a span: ...

Connect a designated button to a designated modal for a seamless user experience

I am struggling to dynamically change the content of a modal based on different buttons being clicked. The issue lies in trying to reference the div element within JavaScript since I can't have multiple elements with the same ID. As a newcomer to JS, ...

What is the best way to arrange the elements of a dropdown list in reverse order?

I have the following code snippet used to retrieve data from a database and display it in a dropdown list: @{ int m = 1; foreach (var item in Model.MessagesList) { if (@item.receiverUserId == userId) { <li> <a class=&qu ...

How to round whole numbers to whole numbers using JavaScript?

Looking to manipulate some numbers in JavaScript. Let's say we have x = 320232, y = 2301, and z = 12020305. The goal is to round these numbers to the nearest tens, hundreds, or thousands place. Thus, we want them to become x = 320000, y = 2300, and z ...

Error: The function $.simpleTicker is not defined

Every time I try to call a jQuery function, an error shows up: Uncaught TypeError: $.simpleTicker is not a function I attempted changing $ to jQuery but it didn't resolve the issue. This represents my jQuery code: (function ($) { 'use ...

Angular's implementation of a web socket connection

I am facing an issue with my Angular project where the web socket connection only opens upon page reload, and not when initially accessed. My goal is to have the socket start as soon as a user logs in, and close when they log out. Here is the custom socke ...