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

时间:2015-01-17 07:33:45

标签: javascript angularjs angularjs-ng-repeat

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

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

{
    "__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
    );
});

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

所以我发现我必须将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>