user3719049 user3719049 - 2 months ago 19
AngularJS Question

Angularjs - unable to push children items dynamically

I have a simple nested json embedded in my html file to which I want to insert some data dynamically using form.

I am able to insert data to parent level but unable to insert to child level. What I am doing wrong?

Here is the code:

<div class="container" ng-app="myApp" ng-controller="myCtrl">
<label>Enter Data</label>
<input ng-model="name" type="text">
<input ng-model="rollno" type="number">
<input ng-model="id" type="text">
<button ng-click="addData(data)">Enter Data</button>
<table class="table table-bordered">
<tr>
<th>Sr No</th>
<th>Name</th>
<th>Roll No</th>
<th>Subjects</th>
<th>Delete</th>
</tr>
<tr ng-repeat="data in myData">
<td>{{$index+1}}</td>
<td>{{data.name}}</td>
<td>{{data.rollno}}</td>
<td ng-repeat="subject in data.subjects">{{subject.id1}}, {{subject.id2}}</td>
<td><a href="" ng-click="removeData($index)">remove</a></td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp',[]);
app.controller('myCtrl',function($scope){
$scope.myData =[{"name":"Jon","rollno":123,"subjects":[{"id1":"Maths","id2":"Hindi"}]},{"name":"Ron","rollno":234,"subjects":[{"id1":"English","id2":"Hindi"}]}];
$scope.addData = function(data){
$scope.myData.push({name:$scope.name,rollno:$scope.rollno,id1:$scope.id1});
}
$scope.removeData = function(index){
$scope.myData.splice(index, 1);
}
});
</script>

Answer

If you are trying to insert subjects as well using addData function you can do the below. In html add those ng-models

    <input ng-model="name" type="text">
    <input ng-model="rollno" type="number">
    <input ng-model="id" type="text">
    <input ng-model="subid1" type="text"/>
    <input ng-model="subid2" type="text"/>

In js

         $scope.addData = function(data){
        var arrData = {name:$scope.name,rollno:$scope.rollno,subjects:[{id1:$scope.subid1,id2:$scope.subid2 }]};
        $scope.myData.push(arrData);
    }
Comments