我正在创建一个有表单的页面,在那里可以修改工作。当页面加载时,将触发以下承诺链,该承诺链获取当前作业数据并填充表单。
我对城市选择有一个问题,因为只有当工作数据返回时,我才知道省和城市值。在这个阶段,创建了另一个承诺来构建城市选择,但是当它被解决时,城市选择的选择值(其中填充了城市)没有被设置为$scope.job。City不确定原因。
api.getJobCategories()
.then(function (responseObject) {
$scope.jobCategories = responseObject.data;
return api.getJob({
job_id: $routeParams.job_id
});
})
.then(function (responseObject) {
$scope.job = responseObject.data;
// $scope.job.city has correct city value
return api.getProvinceCities({
province_name: $scope.job.province,
asJson: true
});
})
.then(function (responseObject) {
// Issue: $scope.job.city has correct value but after building
// the cities select $scope.job.city value is not applied to cities select
$scope.cites = responseObject.data;
});
模板<form name="formjob" class="css-form" novalidate>
... more controls
<!-- Issue job.city model value does not bind to control -->
<select
ng-model="job.city"
ng-options="city.city_name as city.label for city in cites"
name="city"
class="form-control"
required="" >
</select>
</form>
可能的解决方法,因为必须等待所有3个承诺都解决
var job = null;
api.getJobCategories()
.then(function (responseObject) {
$scope.jobCategories = responseObject.data;
return api.getJob({
job_id: $routeParams.job_id
});
})
.then(function (responseObject) {
job = responseObject.data; // store in temp var
return api.getProvinceCities({
province_name: job.province,
asJson: true
});
})
.then(function (responseObject) {
$scope.cites = responseObject.data;
$scope.job = job; // assign job scope only after cites select has been built
});
JB Nizet的建议
var job, city;
job = city = null;
api.getJobCategories()
.then(function (responseObject) {
$scope.jobCategories = responseObject.data;
return api.getJob({
job_id: $routeParams.job_id
});
})
.then(function (responseObject) {
job = responseObject.data;
city = job.city; // store city in temp var
job.city = null; // or delete job.city
$scope.job = job;
return api.getProvinceCities({
province_name: job.province,
asJson: true
});
})
.then(function (responseObject) {
$scope.cites = responseObject.data;
$scope.job.city = city; // reassign city
});
JB Nizet的建议
var job, city;
job = city = null;
api.getJobCategories()
.then(function (responseObject) {
$scope.jobCategories = responseObject.data;
return api.getJob({
job_id: $routeParams.job_id
});
})
.then(function (responseObject) {
job = responseObject.data;
city = job.city; // store city in temp var
job.city = null; // or delete job.city
$scope.job = job;
return api.getProvinceCities({
province_name: job.province,
asJson: true
});
})
.then(function (responseObject) {
$scope.cites = responseObject.data;
$scope.job.city = city; // reassign city
});