I'm trying to share a $http request and return it's value. But it seems like it's 'deferred' and won't set the value.
For this example, I have 2 select box choices of cars. So the controller loads the cars from cars.json whose value is assigned to $scope.cars:
app.controller('MainCtrl', function($scope, $http, LoadCars) {
LoadCars.async().success(function(data) {
$scope.cars = data;
$scope.carA = $scope.carB = data[0];
$scope.carAChanged();
$scope.carBChanged();
});
$scope.carAChanged = function() {
$scope.modelsA = $scope.carModels($scope.carA.c);
}
$scope.carBChanged = function() {
$scope.modelsB = $scope.carModels($scope.carB.c);
}
$scope.carModels = function(code) {
var promise = $http.get(code + '.json')
.success(function(data) {
//$scope.modelsA = data;
return data;
});
return promise;
}
});
HTML:
<fieldset>
<legend>Choice 1</legend>
<div><select ng-model="carA" ng-options="c.name for c in cars" ng-change="carAChanged()"></select></div>
<div><select ng-model="modelA" ng-options="m.c for m in modelsA"></select></div>
</fieldset>
<fieldset>
<legend>Choice 2</legend>
<div><select ng-model="carB" ng-options="c.name for c in cars" ng-change="carBChanged()"></select></div>
<div><select ng-model="modelB" ng-options="m.c for m in modelsB"></select></div>
</fieldset>
Plunker: http://plnkr.co/edit/5CFFGJ?p=preview
If i uncomment the line inside $scope.carModels(), $scope.modelsA loads up fine. But I want the value to return because I need to set modelsB as well separately.
What am I doing wrong? And what's the correct way to achieve this?