Domanda

First steps in AngularJS. I'm facing a strange problem related to this, but the solution doesn't work to me, maybe I'm missing something (as I said, I'm a really n00b with angular).

I'm my HTML, I'm building some radio buttons like that:

<div ng-Controller="PageTwo" >
    <h3>General Information > Knowledge About </h3>
          <div>
        <b>User</b>
        <div>
            <div ng-repeat="option in userOptions">
                <input type="radio" name="userGroups" ng-model="$parent.userSelected" value="{{option.id}}" id="{{option.id}}">{{option.text}}
                        </div>          
            </div>
            Selected thing: {{userSelected}}

        </div>
    </div> 

This is my related Controller:

uxctModule.controller ('PageTwo', function ($scope, ModelData){
    $scope.data = ModelData;
    $scope.userOptions = [{text:'Option 1', id:0}, {text:'Option 2', id:1}, {text:'Option 3',id:2},  {text:'Option 4', id:3}];;
    $scope.userSelected = ModelData.knowledgeAboutUser;
});

The model is the following object

uxctModule.factory ("ModelData", function () {
   var data = {
            // more code here
        knowledgeAboutUser : 3,

   }
   return data
});

Now, the problem is that I'm logging in the console the ModelData object, and I've noticed that it's not updating when clicking the radio buttons. I think the binding it's ok: I've tried to change the value in the Model, and the app selects the corresponding radio button.

Any help it's really appreciated, I'm stuck on this for hours

È stato utile?

Soluzione

You can remove the intermediate variable $scope.userSelected:

<div ng-repeat="option in userOptions">
    <input type="radio" name="userGroups" ng-model="data.knowledgeAboutUser" value="{{option.id}}" id="{{option.id}}">{{option.text}}         
</div>
Selected thing: {{data.knowledgeAboutUser}}

Altri suggerimenti

It working fine

just change

$scope.userSelected

to

$scope.userSelected.selected

Working Code

script

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

app.factory ("ModelData", function () {
   var data = {
            // more code here
        knowledgeAboutUser : 2,

   }
   return data
});

app.controller("PageTwo", function ($scope, ModelData) {
    $scope.userSelected = {};
    $scope.userOptions = [{text:'Option 1', id:0}, {text:'Option 2', id:1}, {text:'Option 3',id:2},  {text:'Option 4', id:3}];;
    $scope.userSelected.selected = ModelData.knowledgeAboutUser;
});

html

<div ng-app="app" ng-Controller="PageTwo">
     <h3>General Information > Knowledge About </h3>

    <div> <b>User</b>

        <div>
            <div ng-repeat="option in userOptions">
                <input type="radio" name="userGroups" ng-model="userSelected.selected" value="{{option.id}}" id="{{option.id}}">{{option.text}}
             </div>
        </div>
            {{userSelected.selected}}
    </div>
</div>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top