Yassine Badache Yassine Badache - 3 months ago 10
AngularJS Question

AngularJS mis-type between model and controller

I am receiving a list of objects from my server with the following format:

[ { 'id' : 1, ... }, { 'id' : 2, ... }, { 'id' : 3, ... } ]


I am trying to allow the user to select objects with a
radio
button. Here is the following HTML code:

<input type="radio" ng-model="id" value={{ obj.id }} />


I am repeating this piece of code for every object in the list. Problem is, when clicking one of the buttons, the following error shows up:

Error: ngModel:numfmt
Model is not of type `number`


The ID of each object is clearly a number, as the following console log states:

console.log(typeof (obj.id)); <- return 'number'


But it still does not work. Can anyone help me discovering why does it break ?

EDIT The code iterating through the array of objects:

<ul ng-repeat="obj in objectList>
<li>
<label><input type="radio" string-to-number ng-model="id" value={{ obj.id }} />
{{ obj.id }}</label>
</li>
</ul>

Answer

The HTML should be:

<ul ng-repeat="obj in objectList">
   <li>
      <input type="radio" name=group1 ng-model="group1.id" ng-value='obj.id' />
      {{ obj.id }
   </li>
</ul>
    <p>Model = {{group1.id}}</p>
</div>

There are several problems with the code

  • The ng-model attribute needs to set to a property of an object. (Use a dot.)

  • Use ng-value for Angular Expressions

  • The radio button group needs to be defined with the name attribute.

The DEMO on JSFiddle.

Comments