我有2个函数第一个用angular控制器启动,第二个从数据库加载一个状态,问题是因为JavaScript是异步的,当我在函数中使用时变量$scope.info.loadState
是未定义的,搜索我找到函数.done
如何解决这个问题,但现在启动控制器时会出现以下错误Error: loadByIdAssetState(...) is undefined
功能代码如下
angular.module('assetModule')
.controller('assetEditCtrl', ['selectedService','assetRESTService'
,'assetStateRESTService','$location', '$modal'
,'$scope', assetEditCtrl]);
function assetEditCtrl (selectedService, assetRESTService, assetStateRESTService, $location, $modal, $scope) {
$scope.file = {};
$scope.data = {};
$scope.info = {};
initCtrl();
function initCtrl() {
$scope.info.selected = {};
if(selectedService.getSelected() != undefined){
$scope.file.asset = selectedService.getSelected();
selectedService.setSelected(undefined);
$scope.info.loadState = loadByIdAssetState($scope.file.asset.assetState_id)
.done(function(state) {
console.log(state);
$scope.file.asset.stateName = state.state;
return state;
});
console.log($scope.info.loadState);
$scope.file.asset.stateName = $scope.info.loadState.state;
}
}
function loadByIdAssetState(stateId) {
assetStateRESTService.getByIdAssetStates(stateId)
.then(function(state) {
console.log(state);
$scope.info.loadStateReady = true;
return state;
})
.catch(function(error) {
console.log(error);
});
}
}
getSelected
是一个返回所选资产的服务,资产有assetState_id,我希望名称为此状态
答案 0 :(得分:0)
看起来您忘记将loadByIdAssetState
注入控制器,您必须这样做才能使用它。这样做:
function initCtrl(loadByIdAssetState) {
$scope.info.loadState = loadByIdAssetState($scope.file.asset.assetState_id).done(function(state) {
console.log(state);
$scope.file.asset.stateName = state.state;
return state;
});
console.log($scope.info.loadState);
$scope.file.asset.stateName = $scope.info.loadState.state;
}