将对象设置为ng-model的ng-options

时间:2014-10-10 20:29:35

标签: javascript jquery angularjs

我有以下HTML:

<div class="row" ng-repeat="question in currentTemplate.questions">
    <div class="col-xs-4" ng-show="editingQuestion[$index]">
        <select style="width:100%;" ng-model="editingCurrentlySelectedAnswerOption[$index]"
        ng-options="answerOption as answerOption.back for answerOption in answerOptions">
        </select>
    </div>
</div>

我想知道如何设置select语句中显示的值。当页面加载时,它应该已经设置,因为我通过for循环来设置editingCurrentlySelectedAnswerOption的值,以便每个都被预先选择([$ index]指的是ng-repeat的索引,这是在里面因为在ng-repeat中有多个选择,我需要在数组中每个ng-repeat一个点来跟踪每个单独的选择),但是它首先作为空白点出现。我使用了ng-init,一个按下按钮时调用的函数,它取消隐藏上面的div,以及页面加载时的函数。我在DOM和console.logs中使用了绑定来检查值。他们似乎都是正确的。 ng-options中的answerOptions是:

var answerOptions = [
    { front: "RadioButton", back: "Multi-Choice" }
    { front: "CheckBox", back: "Multi-Answer" }
    { front: "TextBox", back: "Free Text" }
];

当我打印editCurrentlySelectedAnswerOption [$ index]时,它总是正确地显示一个对象,就像上面的一个对象一样,但由于某种原因,它在加载时总是一个空白的select语句。有什么我不知道ng-options如何与对象一起工作?或者我做错了什么?

更新

我以这种方式设置editingCurrentlySelectedAnswerOption的值:

 this.scope.editingCurrentlySelectedAnswerOption = [];

for (var i in this.scope.currentTemplate.questions) {
if (this.scope.currentTemplate.questions.hasOwnProperty(i)) {
        this.scope.editingCurrentlySelectedAnswerOption.push(this.scope.currentTemplate.questions[i].answerType);
    }
}

我增加this.scope.currentTemplate中存在问题的次数的原因是因为在html中ng-repeat重复了问题的数量。他们应该匹配。

这就是this.scope.currentTemplate.questions [0]的定义方式:

new Utilities.Question(
    "Question1",
    { front: "TextBox", back: "Free Text" },
    ["Yes", "Maybe", "No", "I don't know"],
    [50.0, 25.0, 0.0, -25.0]
)

以下是Utilities.Question的定义:

export class Question {
    question: string;
    answerType: any;
    answerOptions: string[];
    answerWeights: number[];

    constructor(question?: string, answerType?: any, answerOptions?: string[], answerWeights?: number[]) {

        this.question = question;
        this.answerType = answerType;
        this.answerOptions = answerOptions;
        this.answerWeights = answerWeights;

    }

}

1 个答案:

答案 0 :(得分:1)

每个人都是正确的,ng-model / ng-options是指对象的引用而不是值,所以即使两个对象的值是正确的,引用也不一样,因此, select没有看到ng-model变量等于给定的选项。为了解决这个问题,我刚刚在ng-options的末尾添加了一个曲目,现在可以正常工作了。不确定这是否是最佳方式,但它确实有效!感谢大家的帮助!

相关问题