Reputation: 5818
In the below code, I've bound the array data $scope.data.arraydata
to the custom section mysection
.
And, for each arraydata I am binding the textbox with some keys for that array.
e.g. var1, var2
Also on adding multiple sections, the above is working fine.
But when I try to get the scope data with the below, the arraydata
inside $scope.data
is not binding back with the values var1
and var2
angular.element(document.getElementById('form')).scope().data
e.g. Expected Output (on adding 2 sections)
{
"test":"Single Data",
"arraydata":[
[
{
"var1":"aaa",
"var2":"bbb"
}
],
[
{
"var1":"ccc",
"var2":"ddd"
}
]
]
}
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.data = {
"test": "Single Data",
"arraydata": []
}
$scope.addSection = function () {
$scope.data.arraydata.push([]);
}
$scope.addSection();
});
app.directive('mysection', function () {
return {
restrict: 'E',
scope: {
arrdata: "=?"
},
template: $("#SectionTemplate").html()
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<body id="form" ng-app="myApp" ng-controller="myCtrl">
<div>
{{data}}
</div>
<div>
{{ arrdata }}
</div>
<div>
<mysection ng-repeat="arrdata in data.arraydata" ng-model="arrdata"></mysection>
</div>
<button type="button" ng-click="addSection()">Add Section</button>
</body>
<script type="text/ng-template" id="SectionTemplate">
<div style="border: solid 1px red">
{{ arrdata }}
<input type="text" ng-model="arrdata.var1" />
<input type="text" ng-model="arrdata.var2" />
</div>
</script>
Upvotes: 1
Views: 102
Reputation: 4484
I think I see two things in the code:
NgModel is not relevant here. Instead, the directive is expecting arrdata
input binding attribute.
The push
method is pusing an array, and the directive is expecting an object.
Example:
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.data = {
"test": "Single Data",
"arraydata": []
}
$scope.addSection = function () {
$scope.data.arraydata.push({});
}
$scope.addSection();
});
app.directive('mysection', function () {
return {
restrict: 'E',
scope: {
arrdata: "=?"
},
template: $("#SectionTemplate").html()
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<body id="form" ng-app="myApp" ng-controller="myCtrl">
<div>
{{data}}
</div>
<div>
{{ arrdata }}
</div>
<div>
<mysection ng-repeat="arrdata in data.arraydata" arrdata="arrdata"></mysection>
</div>
<button type="button" ng-click="addSection()">Add Section</button>
</body>
<script type="text/ng-template" id="SectionTemplate">
<div style="border: solid 1px red">
{{ arrdata }}
<input type="text" ng-model="arrdata.var1" />
<input type="text" ng-model="arrdata.var2" />
</div>
</script>
Upvotes: 2