gpt4 book ai didi

AngularJS - ngrepeat 中的 ngmodel 未更新 ('dotted' ngmodel)

转载 作者:行者123 更新时间:2023-12-03 08:02:57 27 4
gpt4 key购买 nike

我正在尝试用 Angular 数组绘制 radioBoxes,然后获取选中的 radio 的值,但是模型不会改变它的值吗,有人可以帮我吗?

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>

Angular 部分

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 preventthe child scope from creating its own property. Define a function onthe parent scope, and call it from the child, passing the primitivevalue up to the parent (not always possible)

关于AngularJS - ngrepeat 中的 ngmodel 未更新 ('dotted' ngmodel),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26649364/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com