本文介绍了AngularJS - ngrepeat 中的 ngmodel 未更新('dotted' ngmodel)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用角度数组绘制 radioBoxes,然后获取已检查无线电的值,但模型不会更改其值,您可以帮我吗?

HTML 部分

<div ng-controller="CustomCtrl"><label ng-repeat="user in users"><input type="radio" name="radio" ng-model="radio" value="{{user.name}}"/>{{用户名}}<br/>{{收音机}}<br/><a href="javascript:void(0)" ng-click="saveTemplate()">保存</a>

角部

function CustomCtrl($scope) {$scope.radio = "约翰";$scope.users = [{姓名":约翰",年份":18},{姓名":托尼",年份":19}];$scope.saveTemplate = function() {控制台日志($scope.radio);};}

您可以在此处查看示例 - http://jsfiddle.net/hgf37bo0/2/

解决方案

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

$scope.radio = {姓名:'约翰'}

然后像这样从 html 访问它:

这是一个有效的 jsfiddle

您可以在此答案

中了解为什么需要这样做

来自 angularjs 文档:

作用域继承通常很简单,你通常甚至不需要知道它正在发生......直到你尝试将 2 路数据绑定(即表单元素、ng-model)绑定到一个基元(例如,数字, string, boolean) 在子作用域内在父作用域上定义.它不像大多数人期望的那样工作.发生的情况是子作用域获得了自己的属性,该属性隐藏/隐藏了同名的父属性.这不是 AngularJS 正在做的事情——这就是 JavaScript 原型继承的工作方式.

...

有一个'.'在您的模型中将确保原型继承发挥作用.所以,使用

而不是

如果您确实想要/需要使用原语,有两种解决方法:

在子作用域中使用 $parent.parentScopeProperty.这将防止子范围从创建自己的属性.定义一个函数父作用域,并从子作用域调用它,传递原语价值由父母决定(并非总是可能)

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/

解决方案

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:

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

这篇关于AngularJS - ngrepeat 中的 ngmodel 未更新('dotted' ngmodel)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 14:36
查看更多