I am trying to make a call to the server to get a list of items based on a specific ID selected in a dropdown list.
html:
<tr ng-repeat="parent in model.waivers">
<td><select ng-model="parent.ID" ng-options="object.Key as object.Value for object in model.myObject"></select></td>
<td><select ng-model="parent.ServiceNameID" ng-options="expectedResult.Key as expectedResult.Value for expectedResult in model.output(object.ID)"></select></td>
</tr>
controller:
$scope.model.output = function(id) {
console.log(id);
}
model:
var Model = function() {
this.parent = [];
};
I am just logging it here to see the result. what I really intend to do is get a list based on that id.
if there are 3 table rows then what is output is:
1
1
1
2
2
3
3
1
2
3
1
instead of:
1
2
3
which is what I would expect since there is only one id per line.
Any suggestions on what is causing this behavior?
Update
So @Fieldset informed me that the problem is caused by angular calling the method one time for each item in the parent.
Any suggestions on how to do this only calling the method once per item?
Your code is in a ng-repeat so model.output(object.ID) will be called as many times as there are elements in model.waivers.
You can't do your request to your server like this, because your HTTP request will be asynchronous and return a promise and you can't use a promise in your view. You have to load your data in your controller ($scope), then your view will be able to access to your data through $scope
You have to request data before :
controller
function($scope, $http) {
$scope.data = [];
//This is asynchronous
$http.get('my/path/to/my.data').success(function(data) {
$scope.data = data;
});
}
EDIT:
angular.module('myApp', []).controller('myCtrl', function($scope, $http, $q) {
//One request per id
var ids = [4, 52, 65, 12, 78];
var promises = [];
ids.forEach(function(id) {
promises.push($http.get('my/path/to/my.data?id='+id));
});
//Fill $scope.data when all requests are done
$scope.data = [];
$q.all(promises).then(function(data){
$scope.data = data;
/**
* You get something wich looks like
*
* Assuming that your webservice returns a response like {id: 4, name: 'Something'}
*
* $scope.data = [
* {id: 4, name: 'Something'},
* {id: 52, name: 'Something else'},
* {id: 65, name: 'foo'},
* {id: 12, name: 'bar'},
* {id: 78, name: 'foobar'}
* ];
*
* So you can loop over $scope.data in your view
*
*/
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With