AngularJS – ngrepeat中的ngmodel没有更新(‘dotted’ngmodel)

我正在尝试使用角度数组绘制radioBoxes,然后获得已检查无线电的值,但模型不会改变它的值,任何人都可以帮我这个吗?

HTML部分

<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>

角部

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

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

你可以在这里看到例子 – http://jsfiddle.net/hgf37bo0/2/

解决方法

你需要将$scope.radio设置为这样的对象:

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

然后从html访问它,如下所示:

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

这是一个工作jsfiddle

您可以在answer中了解为什么这是必要的

来自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)

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...