Reputation: 77
I have a list of checkboxes, which are dynamically built from getJson
request.
<tr data-ng-repeat="(key, value) in relatedServices | orderBy:predicate:reverse | filter:search:strict">
<td>
<input type="checkbox" ng-model="array[$index]" ng-true-value="{{value.ID}}" ng-false-value="{{undefined}}" />
</td>
<tr>
Then I would like to check some checkboxes and postJSON
them.
Here is controller code:
var myApp = angular.module('myApp', []);
myApp.controller('JsonController', function ($http, $scope) {
$http.get("/RS/GETJSON/")
.success(function (response) {
$scope.relatedServices = response;
});
$scope.array = [];
var values = $scope.array;
var log = [];
angular.forEach(values, function (value, key) {
this.push('{Id' + ': ' + value + '}');
}, log);
$scope.add = function () {
$http.post("/RS/POSTJSON/", log);
}
});
The problem is when I check the checkboxes, values are $scoped
to the $scope.array = [];
.
But when I run add()
, the log = []
are empty.
How ever if I hardcode values in the script, lets say
$scope.array = ['1','2','3'];
This values do not disappear.
What I am doing wrong?
Upvotes: 0
Views: 1390
Reputation: 2427
The problem with your code is timing, the $http.get is called but the success part is only called once the data is returned. In the meantime execution continues and when you do the forEach $scope.array is still empty. You can move the forEach into the add function but you should also check to see if the data has actually been returned.
var myApp = angular.module('myApp', []);
myApp.controller('JsonController', function ($http, $scope) {
var hasLoaded = false;
$http.get("/RS/GETJSON/")
.success(function (response) {
$scope.relatedServices = response;
hasLoaded = true;
});
$scope.array = [];
$scope.add = function () {
if(!hasLoaded) {
alert('Still waiting');
return;
}
var values = $scope.array;
var log = [];
angular.forEach(values, function (value, key) {
this.push('{Id' + ': ' + value + '}');
}, log);
$http.post("/RS/POSTJSON/", log);
}
});
Upvotes: 4