大家。我有一个奇怪的问题......我的应用程序中有几个状态,它们似乎都可以工作,但在一个 Controller 内部除外。我已经发布了我尝试使用其功能的工厂,以及 Controller 、状态和应该触发该功能的 View :
app.factory('handleShipping', ['$http', function($http){
var handleShipping = {};
handleShipping.validate = function(address){
return ($http.post('/shipping/validate',address).success(function(data){
console.log(JSON.stringify(data));
}));
}
return handleShipping;
}]);
...
app.controller('ValidateCtrl',['$scope','$state', 'handleShipping','shipperName', 'auth',function($scope, $state, handleShipping, shipperName,auth){
$scope.getShipper = function(shipName){
shipperName.shipper = shipName;
};
$scope.validateAddress = function(){
handleShipping.validate($scope.user).error(function(error){
$scope.error = error;console.log('Error!');
}).then(function(){
$state.go('label');
});
};
}]);
...
.state('address', {
url: '/address',
templateUrl: '/address.html',
controller: 'ValidateCtrl'
})
.state('label', {
url: '/label',
templateUrl: '/label.html',
controller: 'LabelCtrl'
});
...
<script type="text/ng-template" id="/address.html">
<div class="page-header">
<h1>Address, please</h1>
</div>
<div ng-show="error" class="alert alert-danger row">
<span>{{ error.message }}</span>
</div>
<form ng-submit="validateAddress()"
style="margin-top:30px;">
<div class="form-group">
<input type="text" class="form-control" placeholder="Street"
ng-model="user.street"></input>
</div>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="City"
ng-model="user.city"></input>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="State" ng-model="user.state"></input>
</div>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Zip Code"
ng-model="user.zipCode">
</input>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</script>
我没有收到错误消息。如果我输入 localhost:3000/label,我可以看到 View 。另外,我注意到一些奇怪的事情……如果我停留在 View “地址”上,然后按下“提交”按钮,则什么也不会发生。但是如果我不理会页面,而应用程序在终端上运行,它会在控制台中随机显示错误消息,而在终端上,我会看到
POST /shipping/validate - - ms - -
如有任何帮助,我们将不胜感激。
最佳答案
工厂方法应该返回一个 promise 。目前您正在服务中使用 success
和 error
回调,它不允许您在验证函数上链式 promise 。您一定在控制台中遇到错误。 $state.go
不工作,因为执行没有转到那一行。
返回 promise 后,您需要在验证方法调用后使用 .then
链接该 promise 。
工厂
handleShipping.validate = function(address){
return $http.post('/shipping/validate',address);
};
Controller
$scope.validateAddress = function(){
handleShipping.validate($scope.user).then(function(data){ //success
//$state.go('label');
}, function(error){ //error
$state.go('label');
})
};
关于javascript - $state.go 不能在单个 Controller 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38295829/