加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:08:20 所属栏目:安全 来源:网络整理
导读:我正在尝试使用角度数组绘制radioBoxes,然后获得已检查无线电的值,但模型不会改变它的值,任何人都可以帮我这个吗? HTML部分 div ng-app div ng-controller="CustomCtrl" label ng-repeat="user in users" input type="radio" name="radio" ng-model="radio"
我正在尝试使用角度数组绘制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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读