Inconsistencies in AngularJS ng-checked functionality

Currently, I am utilizing angularjs in conjunction with an edit view for a form. My goal is to bind the values that were previously used. Below is the code/HTML snippet that I am working with. In addition to angularjs, I am also implementing typescript following the controller as format.

HTML:

<label ng-repeat="type in Ctrl.Types">
    <input type="radio" name="Type" ng-model="Ctrl.Foo.Type" ng-value="type.TypeId" required ng-checked="type.TypeName===Ctrl.Foo.TypeName" />
    {{ type.TypeName }} {{ type.TypeName===Ctrl.Foo.TypeName }}
</label>

Typescript JS For getting Foo

Foo:any;
getFoo = (Fooid) => {
    this.FooResource.getFooById(Fooid).then((response) => {
        this.Foo= response.data;
    });
};

While I am able to retrieve all the values successfully and everything appears to be binding properly, I am encountering an issue with the radio buttons. Upon inspecting the HTML element, I notice that the radio button is set to checked="checked". Furthermore, I have confirmed that the expressions in the HTML output as expected. However, the radio button selected state (the dot indicating selection) seems to be inconsistent. There are times when it works as intended, but other times it does not. It appears that the types load and Foo load at different times, which could be a contributing factor.

Answer №1

When working with radio buttons, it is important to properly bind the values to avoid inconsistent behavior. In the code snippet provided, the usage of ngModel and ngValue to bind multiple values to the radio button can lead to unexpected results.

Here is an alternative approach:

<label ng-repeat="type in Ctrl.Types">
    <input type="radio" name="Type" ng-model="type.TypeId" required ng-checked="type.TypeName===Ctrl.Foo.TypeName" />
    {{ type.TypeName }} {{ type.TypeName===Ctrl.Foo.TypeName }}
</label>

or

<label ng-repeat="type in Ctrl.Types">
    <input type="radio" name="Type" ng-value="type.TypeId" required ng-checked="type.TypeName===Ctrl.Foo.TypeName" />
    {{ type.TypeName }} {{ type.TypeName===Ctrl.Foo.TypeName }}
</label>

Refer to the documentation for more information.



----EDIT----
Consider this revised code without using ngChecked:

<div ng-app ng-controller="myCtrl">
    <label>Enter a character</label>
    <input type="text" ng-model="Ctrl.Foo.TypeName">
    <div ng-repeat="type in Ctrl.types">
        <input type="radio" name="Type" ng-model="Ctrl.Foo.TypeName" ng-value="type.TypeName" required />{{type.TypeName}}
    </div>
</div>


View the interactive example on JSFiddle.

Answer №2

To resolve this issue, I made a modification by creating a function within ng-checked instead of using an expression. In the function, I checked for a condition and returned true or false. Additionally, I made sure to set the ng-model to the selected value before returning. This important step was previously overlooked, as shown in the example below.

<label ng-repeat="type in Ctrl.Types">
    <input type="radio" name="Type" ng-model="Ctrl.Foo.Type" ng-value="type.TypeId" required ng-checked="Ctrl.isTypeChecked(type)" />
    {{ type.TypeName }}
</label>

JS:

isTypeChecked = (t) => {   
    if (t.TypeName === this.Foo.TypeName) {
        this.Foo.Type = t.TypeId;
    }    
    return t.TypeName === this.Foo.TypeName;
};

The getFoo function remains unchanged from its previous state.

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

Retrieve the initial element from a JSON object to identify errors, without being dependent on its specific key name

Utilizing AngularJS, my JSON call can result in various errors. Currently, I am handling it like this: $scope.errors = object.data.form.ERRORS or $scope.errors = object.data.system.ERRORS However, in the future, 'form' or 'system' ...

Strategies for effectively mocking an Angular service: During Karma Jasmine testing, ensure that the spy on service.getShipPhotos is expected to be called once. In the test, it should

Currently, I am working on testing a function called getSingleShip in Angular 12 using Karma-Jasmine 4. The aim is to verify if this function is being called by another function named retrieveShip. However, the test results indicate that getSingleShip has ...

Ways to prevent scrolling in Angular 6 when no content is available

I am developing an angular 6 application where I have scrollable divs containing: HTML: <button class="lefty paddle" id="left-button"> PREVIOUS </button> <div class="container"> <div class="inner" style="background:red">< ...

What steps should I follow to bring a telegram bot to life? Is it an issue if I try to integrate a module from Deno

import { TelegramBot, UpdateType } from "https://deno.land/x/telegram_chatbot/mod.ts"; <--- ISSUE import "https://deno.land/x/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6a2a9b299a3a8b086f6e8f4e8f6"> ...

I need to compile a comprehensive inventory of all the publicly accessible attributes belonging to a Class/Interface

When working with TypeScript, one of the advantages is defining classes and their public properties. Is there a method to list all the public properties associated with a particular class? class Car { model: string; } let car:Car = new Car(); Object. ...

What is the best way to retrieve information utilizing Http.get within my project?

I have a TypeScript file containing user data: File path: quickstart-muster/app/mock/user.mock.ts import {User} from "../user"; export const USERS:User[]=[ new User(....); ]; I have a service set up at: quickstart-muster/app/services/user.service.ts ...

How can I implement the vm. syntax using ControllerAs in my application?

After reading various sources, including a few discussions on Stack Overflow, I have come to understand that the ControllerAs syntax is gaining popularity as it aligns with how things are done in Angular 2. Therefore, I decided to delve deeper into unders ...

What is the alternative parameter to use instead of onChange in React Router v4?

Having an issue with the onChange Prop in TypeScript and React JS: I am encountering an error message saying "No overload matched this call." <HashRouter> <Switch> <Route path="/" ...

Interactive form control for location details including country, state, district, and town

I am struggling with adding dynamic form controls on dropdown change. I have been able to add them, but encountered an error preventing me from retrieving the value in 'formName.value'. The specific error message states: "Error: There is no Form ...

Neglect variables that have not been declared (TypeScript)

Currently, I am working on developing a WebExtension using TypeScript that will be later compiled into JavaScript. This extension relies on one of the browser APIs offered by Firefox, specifically the extension API. An example of this is my use of the get ...

Incorporating AngularJS into your current JavaScript code base

We have a JavaScipt project underway that could greatly benefit from incorporating AngularJS. However, due to the size of the project, completely rewriting it in Angular is not feasible. Does anyone have any suggestions or tips on how to integrate Angula ...

Errors can occur when using TypeScript recursive types

Below is a simplified version of the code causing the problem: type Head<T> = T extends [infer U,...unknown[]] ? U : never; type Tail<T> = T extends [unknown,...infer U] ? U : []; type Converter = null; type Convert<T, U extends Converter& ...

Ways to include various inputs with chip

I am currently working on a project that involves implementing an email field using the chip component. However, I have encountered an issue where pasting multiple email values for the first time inserts them into the field successfully. But when I try to ...

In React-Native, implement a function that updates one state based on changes in another state

I need to trigger a function when a specific state changes. However, I encountered the error 'maximum update depth reached'. This seems illogical as the function should only respond to changes from stateA to update stateB. I attempted using setSt ...

AngularUI design pattern for redirecting to a URL post login

In a particular scenario, a user is able to input a URL like: http://localhost:8080/#/component?id=1234 Initially, AngularUI checks if the user has authorization. If not authorized, they are redirected to the login page using the following code: $state. ...

Is it possible for recursive type definitions to handle generics effectively?

I have identified what I believe to be a bug in Typescript and have submitted it as an issue here. Considering that this might not get resolved quickly, I am reaching out for suggestions. Does anyone know of a better solution or workaround than the one pro ...

To enhance VS IntelliSense and type checking in react-intl's FormattedMessage component, assign an id that aligns with a custom TypeScript interface

Due to the limitations of react-localization in terms of date and number formats, as well as its heavy reliance on a single developer, our team made the decision to transition to react-intl for a more stable long-term solution. Check out the contributors ...

The AngularJS directive seems to be having trouble receiving the data being passed through its scope

Check out this HTML code snippet I created: <div ng-controller="ctrl"> <custom-tag title = "name" body = "content"> </custom-tag> </div> Take a look at the controller and directive implementation below: var mod = angular.mod ...

Manipulating Hyperlinks outside the Angular JS applicationIn certain cases, Angular JS

This is my first attempt at creating a single page app. The app's content is contained within the page like a widget, functioning similar to pagination. In the header, I have links that are not related to the angular app. The link structure looks lik ...

Submitting a form from a non-AngularJS application to an AngularJS app requires URL rewriting

I am facing a challenge with my AngularJS search application. The search box is located on a standard HTML page that is not part of the AngularJS framework. Here is how the input field looks: <form accept-charset="UTF-8" name="search" id="search" act ...