一尘不染

如何在AngularJS中设置动态模型名称?

angularjs

我想用一些动态问题来填充表单(在此处提示):

<div ng-app ng-controller="QuestionController">
    <ul ng-repeat="question in Questions">
        <li>
            <div>{{question.Text}}</div>
            <select ng-model="Answers['{{question.Name}}']" ng-options="option for option in question.Options">
            </select>
        </li>
    </ul>

    <a ng-click="ShowAnswers()">Submit</a>
</div>
​
function QuestionController($scope) {
    $scope.Answers = {};

    $scope.Questions = [
    {
        "Text": "Gender?",
        "Name": "GenderQuestion",
        "Options": ["Male", "Female"]},
    {
        "Text": "Favorite color?",
        "Name": "ColorQuestion",
        "Options": ["Red", "Blue", "Green"]}
    ];

    $scope.ShowAnswers = function()
    {
        alert($scope.Answers["GenderQuestion"]);
        alert($scope.Answers["{{question.Name}}"]);
    };
}​

一切正常,除了模型实际上是Answers [“ {{question.Name}}”],而不是评估后的Answers [“
GenderQuestion”]。如何动态设置型号名称?


阅读 221

收藏
2020-07-04

共1个答案

一尘不染

http://jsfiddle.net/DrQ77/

您只需将javascript表达式放入中ng-model

2020-07-04