ng-repeat中的范围未定义

时间:2016-10-12 15:35:22

标签: angularjs angularjs-ng-repeat

在下面的代码中,我试图在每个ng-repeat的末尾创建一个表单,并为范围赋值。

由于某种原因,我正在分配的值(使用ng-model)未被传递。

如果你喜欢小提琴: https://jsfiddle.net/U3pVM/27716/

否则这里是代码:

app.js:

var app = angular.module('qmaker', []);

app.controller('MainCtrl', [
'$scope',
function($scope){

$scope.qstnrs = [
    //object #1
    {
    title:  'questionnaire 1',
    author: 'dave',
    questions:
        [
        {qid: 1, qtype: 'multi'},
        {qid: 2, qtype: 'cross'}
        ]
    },

    //object #2
    {
    title: 'questionnaire 2',
    author: 'raul',
    questions:
        [
        {qid: 1, qtype: 'lol'},
        {qid: 2, qtype: 'foreal'}
        ]
    }
];

$scope.newQuestion = function(index) {
    console.log($scope.type);
    var question_id = $scope.qstnrs[index].questions.length +1;
    $scope.qstnrs[index].questions.push({
            qid:  question_id,
            qtype: $scope.type
        }
    );

};

$scope.newQstnr = function () {
    $scope.qstnrs.push({
        title: $scope.title,
        author: 'admin',
        questions: []
    });
    $scope.title = '';
};
}]);

当我尝试将$scope.type记录到控制台时,我收到 undefined

这是HTML:

<html>
 <head>
    <title>QMaker app</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
    <script src="app.js"></script>
 </head>
 <body ng-app="qmaker" ng-controller="MainCtrl">
    <!-- This form works fine, the next is problematic -->
    <form ng-submit="newQstnr()">
        <input required type="text" ng-model="title">
        <button type="submit">New Questionnaire</button>
    </form>

    <div ng-repeat="qstnr in qstnrs">
        {{qstnr.title}} by {{qstnr.author}}<br>
        <ul ng-repeat="question in qstnr.questions">
            <li>#{{question.qid}}: {{question.qtype}}</li>
        </ul>
        <!-- Form we're speaking about -->
        <form ng-submit="newQuestion($index)">
            <input required type="text" ng-model="type">
            <button type="submit">[+] Question</button>
        </form>
    </div>
 </body>
</html>

当我们尝试在问卷中添加新问题时,该类型不会出现,或者显示为未定义。

为什么会发生这种情况?如何才能使其发挥作用?

1 个答案:

答案 0 :(得分:1)

将表单更改为:

<form ng-submit="newQuestion($index, type)">
  <input required type="text" ng-model="type">
  <button type="submit">[+] Question</button>
</form>

你的功能:

$scope.newQuestion = function(index, type) {
    var question_id = $scope.qstnrs[index].questions.length +1;
    $scope.qstnrs[index].questions.push({
            qid:  question_id,
            qtype: type
        }
    );

};

它的工作原理......我的预感是它在ng-model的ng-repeat中创建了一个新的范围,这样所有重复的输入都不会共享相同的值。否则,当您键入一个文本框时,所有重复的文本框都将显示相同的值。

实际上,我通过将表格更改为:

来证明了这种情况
<form ng-submit="newQuestion($index)">
  <input required type="text" ng-model="$parent.type">
  <button type="submit">[+] Question</button>
</form>

添加$parent会将其附加到父作用域。这样做,你会发现你的逻辑有效,但我正在谈论意想不到的结果。

相关问题