2016-10-12 26 views
0

在下面的代碼中,我試圖在每個ng-repeat的末尾創建一個表單,併爲該作用域賦值。ng-repeat中的作用域未定義

出於某種原因,我分配的值(與ng模型)沒有被傳遞。

如果你喜歡小提琴: 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安慰我收到未定義

下面是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

您的形式改成這樣:

<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-repeat了一個新的範圍ng模型,以便重複的所有輸入不共享相同的值。否則,當您鍵入一個文本框時,所有重複的文本框將顯示相同的值。

事實上,我證明了這是通過改變形式此情況下:

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

添加$parent它附加到母體範圍。這樣做,你會發現你的邏輯起作用,但是我正在談論意外的結果。

+1

(與'console.log(類型)'但是它應該更好地工作) – ValLeNain

+0

感謝您捕捉那... – Zach