Angular js:添加嵌套数组属性列表

时间:2014-07-16 07:55:26

标签: javascript jquery asp.net-mvc angularjs frontend

请帮忙:一路打我的头,我是一个新的蜜蜂角js,用角度js建立一个测验应用,
我在向控制器添加嵌套属性数组时遇到了问题

jsfiddle link showing the issue:

逐步情景

  • 我想添加问题
  • 每个问题都有 4个选项,其中1个被选为正确
  • 我能够获取用户界面,但绑定不适用于选项

html如下:

<div ng-app>
<div class="new-question-container" ng-controller="newQuestionController">
    <h3>Add New Question</h3>
    <form class="new-question-form" novalidate name="newQuestionForm" data-ng-submit="save()">
        <div>
            <label for="QuestionDescription">Quesiton Description</label>
            <input type="text" name="QuestionDescription" data-ng-model="newQuestion.QuestionDescription" required />
        </div>

        Options<br/>
        <div ng-repeat="i in [1,2,3,4]">
            <label for="options[i].OptionDescription">Option {{i}}</label>
            <input name="options[i].OptionDescription" type="text" data-ng-model="options[i].OptionDescription" required />
            Is right answer:
            <input type="radio" data-ng-model="options[i].IsAnswer" name="newQuestion" ng-value="true" />Yes
            <input type="radio" data-ng-model="options[i].IsAnswer" name="newQuestion" ng-value="false" />No
        </div>
        <input type="submit" class="btn btn-primary" value="Add Question" data-ng-disabled="newQuestionForm.$invalid" />
        <a href="#/" class="btn btn-secondary">Cancel</a>

    </form>
    </div>
</div>

角度脚本如下

    function newQuestionController($http, $scope, $window) {
    $scope.newQuestion = {};
    $scope.options = [{}];

    $scope.save = function () {
        $scope.newQuestion.Options.push(options);
        alert($scope.newQuestion.QuestionDescription);
    }
}

1 个答案:

答案 0 :(得分:1)

您必须按照以下方式初始化$scope

$scope.options = [{},{},{},{}];

并将ng-repeat数组更改为从0开始:

ng-repeat="i in [0,1,2,3]"

Here你可以找到一个有效的例子