Airwavezx Airwavezx - 8 days ago 4x
AngularJS Question

Scope inside ng-repeat isn't being defined

In the following code I'm trying to create a form at the end of each ng-repeat and assign a value to the scope.

For some reason the value I'm assigning (with ng-model) isn't being passed.

If you prefer fiddle:

otherwise here is the code:


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

app.controller('MainCtrl', [

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

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

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


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

When I try to log
to console I receive undefined.

Here is the HTML:

<title>QMaker app</title>
<script src=""></script>
<script src="app.js"></script>
<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>

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

When we attempt to add a new question to a questionnaire, the type doesn't appear, or appears undefined.

Why does this happen and how can I make it work?


Change your form to this:

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

And your function to this:

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


And it works... My hunch is that it creates a new isolate in the ng-repeat for the ng-model so that all the inputs that are repeated don't share the same values. Otherwise, when you type in one textbox, all the repeated textboxes would show the same value.

Actually, I proved this is the case by changing the form to this:

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

Adding the $parent attaches it to the parent scope. Do that and you'll see that your logic works but with the unexpected result I was talking about.