我正在尝试共享一个 $http 请求并返回它的值。但它似乎是“延迟的”并且不会设置值。
对于这个例子,我有 2 个选择框选择汽车。因此,控制器加载cars.json
其值被分配给的汽车$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
如果我取消注释里面的行$scope.carModels()
,$scope.modelsA
加载正常。但我希望该值返回,因为我也需要modelsB
单独设置。
我究竟做错了什么?实现这一目标的正确方法是什么?