使用 ng-repeat 在动态单选按钮上设置值

Setting value on dynamic radio button with ng-repeat

我在将动态创建的单选按钮组中的值设置为对象时遇到问题。 当 ng-model 中指定的对象不为 null 时,单选按钮不会被选中,并且单击任何单选按钮都不会触发附加的 $watch。但是,如果加载时 ng-model 中的对象为 null,则 $watch 似乎工作正常。现在,如果我将 ng-model 的值更改为字符串,它工作正常,问题是我需要整个对象。基本上每个模型都是一个问题,当 UI 中的问题发生变化时,整个模型对象将发送到网络服务。

数据(值已设置 - 不起作用)

{
    "__type": "RadioQuestion:#MyProject.Model.Entities",
    "Id": "ff3234ba-40fe-43e3-9457-ea5e3b5ae5a7",
    "Question": "Question goes here",
    "RangeMaxText": "Very likely",
    "RangeMinText": "Not Likely",
    "Title": "Question headline",
    "DefaultValue": {
        "Id": "id-for-no-value",
        "Name": "Nej"
    },
    "PossibleValues": [
        {
            "Id": "id-for-yes-value",
            "Name": "Yes"
        },
        {
            "Id": "id-for-no-value",
            "Name": "No"
        }
    ],
    "Question": "Hows it hanging?",
    "Value": {
        "Id": "id-for-no-value",
        "Name": "Nej"
    }
}

标记

<h4>{{question.Question}}</h4>
<label data-ng-repeat="pValue in question.PossibleValues" for="{{question.Id}}-{{pValue.Id}}">
    <input
        id="{{question.Id}}-{{pValue.Id}}"
        name="radio-for-{{question.Id}}"
        type="radio"
        data-ng-value="pValue"
        data-ng-model="question.Value" />
        {{pValue.Name}}
</label>

数据(值为空 - 有效)

{
    "__type": "RadioQuestion:#MyProject.Model.Entities",
    "Id": "ff3234ba-40fe-43e3-9457-ea5e3b5ae5a7",
    "Question": "Question goes here",
    "RangeMaxText": "Very likely",
    "RangeMinText": "Not Likely",
    "Title": "Question headline",
    "DefaultValue": {
        "Id": "id-for-no-value",
        "Name": "Nej"
    },
    "PossibleValues": [
        {
            "Id": "id-for-yes-value",
            "Name": "Yes"
        },
        {
            "Id": "id-for-no-value",
            "Name": "No"
        }
    ],
    "Question": "Hows it hanging?",
    "Value": null
}

这是手表功能:

this.$scope.questions.forEach((question) => {
    this.$scope.$watch(
        () => { return question; },
        (newVal, oldVal) => this.updateQuestion(newVal, oldVal),
        true
    );
});

据我所知,动态生成的元素在 AngularJS 1.2 中不是一个选项。应该在 1.3 中正常工作。

所以我发现我必须将 Id 属性 用于 Value 对象的 ng-value 和 ng-model 才能完成这项工作

<label data-ng-repeat="pValue in question.PossibleValues" for="{{question.Id}}-{{pValue.Id}}">
    <input class="field radio"
        id="{{question.Id}}-{{pValue.Id}}"
        name="radio-for-{{question.Id}}"
        type="radio"
        data-ng-value="pValue.Id"
        data-ng-model="question.Value.Id" />
    {{pValue.Name}}
</label>