AngularJS - ngmodel in ngrepeat not updating ('

2019-02-25 12:25发布

问题:

i'm trying to draw radioBoxes with angular array, and after that get value of checked radio, but model don't change its value you, can anyone help me with this ?

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 example here - http://jsfiddle.net/hgf37bo0/2/

回答1:

you need to set $scope.radio to be an object like this:

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

and then access it from html like so:

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

here's a working jsfiddle

You can read up on why this is necessary in this answer

from angularjs docs:

Scope inheritance is normally straightforward, and you often don't even need to know it is happening... until you try 2-way data binding (i.e., form elements, ng-model) to a primitive (e.g., number, string, boolean) defined on the parent scope from inside the child scope. It doesn't work the way most people expect it should 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 something AngularJS is doing – this is how JavaScript prototypal inheritance works.

...

Having a '.' in your models will ensure that prototypal inheritance is in play. So, use

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

rather than

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

If you really want/need to use a primitive, there are two workarounds:

Use $parent.parentScopeProperty in the child scope. This will prevent the child scope from creating its 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)