微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐