Utilizing ng-model to bind object values from radio inputs

Dealing with a JSON file:

$scope.favoriteThings = [
    {nr: 1, text: "Raindrops on roses"},
    {nr: 2, text: "Whiskers on kittens"},
    {nr: 3, text: "Bright copper kettles"},
    {nr: 4, text: "Warm woolen mittens"},
    {nr: 5, text: "Brown paper packages tied up with strings"},
    {nr: 6, text: "Cream colored ponies"},
    {nr: 7, text: "Crisp apple streudels"},
    {nr: 8, text: "Doorbells"},
    {nr: 9, text: "Sleigh bells"},
    {nr: 10, text: "Schnitzel with noodles"},
    {nr: 11, text: "Wild geese that fly with the moon on their wings"},
    {nr: 12, text: "Girls in white dresses with blue satin sashes"},
    {nr: 13, text: "Snowflakes that stay on my nose and eyelashes"},
    {nr: 14, text: "Silver white winters that melt into springs"}
  ];

- Utilizing the ng-repeat directive to iterate through the array above.

<li ng-repeat="thing in favoriteThings">
        <input type="radio" value="{{thing}}" ng-model="$parent.selected" name="stuff"/>
          {{thing.text}}
      </li>

- Displaying the selected checkbox's value as

Selected thing: {{selected}}{{selected.nr}}

  • This leads to the following output:

Selected thing: {"nr":5,"text":"Brown paper packages tied up with strings"}
When trying to access the "nr" attribute using {{selected.nr}}, it does not work Any suggestions as to why? PLUNKER LINK EDIT: Also aiming to access the TEXT attribute

Answer №1

To make changes to your HTML body, follow these steps:

      <body ng-controller="MainCtrl">
        <ul>
          <li ng-repeat="thing in favoriteThings">
            <input type="radio" value="{{thing.nr}}" ng-model="$parent.selected" name="stuff"/>
              {{thing.text}}
          </li>
        </ul>
        <hr/>
        Selected thing: {{selected}}  {{getText(selected)}}
      </body>

Additionally, include this function in your controllers:

      $scope.getText  = function(_nr){
          var found = $filter('filter')($scope.favoriteThings, {nr: _nr}, true);
          return found[0].text
        }

For a demonstration of how it works, you can visit the following link on Plunker: Plunker

Answer №2

Make a simple change by replacing the value attribute with the ng-value directive:

 <body ng-controller="MainCtrl">
    <ul>
     <li ng-repeat="thing in favoriteThings">
        <!-- Swap out interpolated value
        <input type="radio" value="{{thing}}" ng-model="$parent.selected" name="stuff"/>
        -- for the ng-value directive -->
        <input type="radio" ng-value="thing" ng-model="$parent.selected" name="stuff"/>
          {{thing.text}}
      </li>
    </ul>
    <hr/>
    Selected thing: {{selected}}<br>
    Number: {{selected.nr}}<br>
    Text:   {{selected.text}}
  </body>

Instead of using interpolation, value={{thing}}, which converts the thing object to a string, the ng-value directive maintains the integrity of the object.

Check out the DEMO on PLNKR

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 issue persists with UIkit modal element remaining in the DOM even after the parent component in Vue.js is destroyed

In my Vue app, I am utilizing the UIKit modal. UIkit.modal(element).show(); // This adds the class uk-open and sets style to display:block UIkit.modal(element).hide(); When I hide the modal, it simply removes the class uk-open and the inline style of dis ...

Having Trouble with Click Function: Loading Pages into Div using Jquery/Ajax

Struggling to load content from other pages into a specific div by clicking on a URL link? Despite having previously executed the code successfully, it seems to redirect to the linked page instead of loading in the desired div. Even with an alarm set up as ...

The `getScript` function in jQuery is not working as expected, even though the path is accurate and the script was successfully downloaded

Recently, I created a website using Mustache.js and incorporated templates loaded via AJAX with jQuery. During the testing phase on my local environment, everything worked perfectly. However, upon uploading the site to my school server, an issue arose whe ...

Retrieving Data from Outside Source using AngularJS

Is there a way to retrieve JSON-Text-Stream data from a specific URL (e.g. SOMEURL/ean.php?id=4001513007704)? The returned result typically appears as follows: { "product": { "ean_id": "4001513007704", "title": "Gerolsteiner Mineralw ...

Sort the data in Angular JS by one key, but ensure that results with another key set to 0 remain at the end

Here is an array of objects containing information about various car brands: $scope.cars = [ {"brand":"McLaren","price":70,"stock":0}, {"brand":"Renault","price":10,"stock":0}, {"brand":"Ferrari","price":100,"stock":3}, {"brand":"Lamborghini","pri ...

Leveraging Bootstrap Modal in a one-page AngularJS application

I am currently working on a single page application in AngularJS using ui.router, and I am looking to incorporate Bootstrap Modals into my app. I have tried following the instructions from this link: http://angular-ui.github.io/bootstrap/#/getting_started ...

Retrieving AJAX data in a Node.js environment

In my HTML application, I am utilizing AJAX to showcase the output on the same page after the submit button is clicked. Before submitting, I am able to retrieve the values passed in the HTML form using: app.use(express.bodyParser()); var reqBody = r ...

Contrasting onevent with addEventListener

After studying various DOM events, I attempted to implement the 'blur' event on the HTML body. My first attempt was with onblur document.body.onblur = () => { dosomething(); } and I also tried using AddEventListener document.body.addEven ...

What is the best way to share both text and an image URL in a single tweet through the Twitter API

Currently, I am utilizing the Twitter API Client for node which includes both the REST and Streaming API. You can find more information about this client by visiting this link. Specifically, I am working with the twit API in conjunction with nodejs. My go ...

Using ng-repeat within another ng-repeat allows elements to be displayed as siblings

My goal is to create a structured list using angularjs: Parent 1 Group1 Child1 Child2 Child3 Child4 Group2 Child1 Child2 Parent 2 Group1 Child1 Child2 Group2 Child1 I have data organized in a similar format like this. $scope.parents = [{ name:&apos ...

Can the useNavigation hook be used to navigate to a class component in React?

How can I use the useNavigation hook to navigate to a class component? Here is my class: export default class AzureLogin extends React.Component I want to navigate to AzureLogin from Screen1. What is the correct way to achieve this? import { useNavigati ...

Retrieve the value of a variable in a Bootstrap modal using Jade

I am looking to accomplish the following: On my Jade page, I have a for-loop that generates a list of items. Each item has some information displayed through Jade variables and a delete button. When this delete button is clicked, I want a Bootstrap Modal ...

Managing value state with several Formik forms within a single component

I'm currently in the process of constructing a web page using React and Formik. Within this form page, I have integrated three distinct Formik forms that are conditionally displayed based on a switch statement. The reason behind structuring it this wa ...

the object '[object Object]' of a distinct supporting nature

I encountered an error stating "ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." This is my TypeScript file: this.list = data.json(); ...

Error in Next.js: The element type is not valid. Please make sure it is either a string (for built-in components) or a class/function (for composite components) and not undefined

I've encountered an issue while working on my Next.js project where I am trying to import the Layout component into my _app.js file. The error message I received is as follows: Error: Element type is invalid: expected a string (for built-in componen ...

Addressing the issue with this.setState and this.state on the Registration page

I am facing an issue with my Registration Page code. I am trying to send data to a database using this.setState and this.state, but every time I run the code, it shows an error in the onSubmit function related to this.state. Can someone please help me unde ...

Automatically resizing font to fit the space available

I am attempting to achieve the task described in the title. I have learned that font-size can be set as a percentage. Naturally, I assumed that setting font-size: 100%; would work, but unfortunately it did not. For reference, here is an example: http://js ...

Utilizing Array in ReactJS with the Power of Hooks

My current situation involves having an array of FooBar objects interface FooBar { foo: string, bar: string, correct: string, other: string[] } const [arrOfObj, setArrOfObj] = useState<FooBar[]>([ { "foo": "fool ...

PHP-based user interface queue system

I am in the process of developing a website that enables users to manipulate a webcam by moving it from left to right. Each user will have a one-minute window to control the camera. I plan on implementing a queuing system on the site to ensure that users ...

Underscore performs calculations and outputs a fresh object as a result

Here is an example of a time series: [ { "_id": { "action": "click", "date": "2015-02-02T00:00:00+01:00" }, "total": 5 }, { "_id": { "action": "hit", "date": "2015 ...