0
<div ng-repeat="class in classses">
    <p>{{class.className}}</p>
    <form novalidate>
        <div ng-repeat="studentInput in class.students track by $index">
            <input type="text" ng-model="studentInput[$index]" typeahead="student as (student.lastName + ', ' + student.firstName) for student in findStudents($viewValue)"/>
        </div>
        <button type="button" ng-click="addStudent(class)">Add Student</button>
    </form>
</div>

In the controller I have:

$scope.addStudent = function(class){
    class.students.push({});
}

I'm using typeahead from angular bootstrap so it returns student objects that I then want to add to the student array of whatever class the form is under. The data is a bunch of class objects that each have a students property which is an array of student objects. At this point, a student object is being added to another object. So it looks like, [0:{firstName: "first", lastName: "last", ...}] instead of [{firstName: "first", lastName: "last", ...}]

Is this a good way of doing this and why is it nesting an object within an object?

1 Answer 1

0

It's an object in an object because of Javascripts nature, it passes object as a "copy of a reference" If it would change the object itself this change will only be made in the (Javascript, not AngularJs) scope of the function. Outside this function your values won't have changed at all. If you change fields of this object they will be persistent also outside your function A good description Does Javascript pass by reference?

Not the answer you're looking for? Browse other questions tagged or ask your own question.