AngularJS - ngmodel in ngrepeat is not updating ('dotted' ngmodel)

I'm trying to draw radioBoxes with an angular array, and after that get the value of the checked radio, but the model doesn't change its value, can anyone help me with that?

HTML part

<div ng-app>
    <div ng-controller="CustomCtrl">
        <label ng-repeat="user in users">
            <input type="radio" name="radio" ng-model="radio" value="{{user.name}}" /> {{user.name}} 
        </label>
        <br/>
        {{radio}}
        <br/>
        <a href="javascript:void(0)" ng-click="saveTemplate()">Save</a>
    </div>
</div>

      

Angular Part

function CustomCtrl($scope) {
    $scope.radio = "John";
    $scope.users = [
        {"name" : "John", "Year" : 18},
        {"name" : "Tony", "Year" : 19}
    ];

    $scope.saveTemplate = function() {
        console.log($scope.radio);
    };
}

      

you can see an example here - http://jsfiddle.net/hgf37bo0/2/

+3


source to share


1 answer


you need to set $scope.radio

as an object:

$scope.radio = {
  name: 'John'
}

      

and then access it from html like this:

<input type="radio" name="radio" ng-model="radio.name" value="{{user.name}}" />

      

jsfiddle works here

You can read why it is needed in this answer



from angularjs docs :

Region inheritance is usually straightforward, and you often don't even need to know that this is happening ... until you try binding two-way binding (i.e. form elements, ng-model) to a primitive (e.g. number, string, boolean) defined in the parent area from within the content area. It doesn't work the way many expect it to work. What happens is that the child scope gets its own property that hides / shadows the parent property of the same name. This is not what AngularJS does - this is how JavaScript prototypal inheritance works.

...

The presence of the '.' in your models will ensure that prototypal inheritance is in play. So use

<input type="text" ng-model="someObj.prop1"> 

      

but not

<input type="text" ng-model="prop1">

      

If you really need / need to use a primitive there are two ways:

Use $ parent.parentScopeProperty on content area. This will prevent the child's sphere from creating their own property. Define a function on the parent scope and call it from the child, passing the primitive value up to the parent (not always possible)

+7


source







All Articles