在我的ui-bootstrap模式中,我有3个modal-body
div。
<div class="modal-body" ng-show="$ctrl.selected.item == 'registration'">...</div>
<div class="modal-body" ng-show="$ctrl.selected.item == 'thanks'">...</div>
<div class="modal-body" ng-show="$ctrl.selected.item == 'error'">...</div>
通过更改$ctrl.selected.item
我在模态窗口中更改HTML。现在我需要在registerService中更改这个变量(对象的属性),注册到registerwindow'控制器。
app.service('registerService', ['$http', 'localStorageService', function ($http, localStorageService) {
this.registerUser = function (registerInfo) {
$http({
url: 'http://localhost:3000/v1/sign_up',
headers: {
'Content-Type' : 'application/json'
},
method: 'POST',
data: {
email: registerInfo.email,
nick: registerInfo.nick,
password: registerInfo.password,
password_confirmation: registerInfo.password_confirmation
}
})
.then(function successCall(response) {
console.log('user added'); // delete it
$ctrl.selected.item = $ctrl.items[1];
}, function errorCall(respone) {
console.log('error callback register ');
console.log(respone.data);
$ctrl.selected.item = $ctrl.items[2];
})
};
}]);
使用$ctrl.selected.item = $ctrl.items[1];
的这种方法显然不起作用..我该怎么做?我不知道我需要异步执行此操作。
答案 0 :(得分:0)
您可以使用Angular的$q
服务来处理此问题。服务的方法如下所示:
this.registerUser = function (registerInfo) {
var deferred = $q.defer();
$http({
url: 'http://localhost:3000/v1/sign_up',
headers: {
'Content-Type' : 'application/json'
},
method: 'POST',
data: {
email: registerInfo.email,
nick: registerInfo.nick,
password: registerInfo.password,
password_confirmation: registerInfo.password_confirmation
}
})
.then(function successCall(response) {
console.log('user added'); // delete it
//$ctrl.selected.item = $ctrl.items[1];
deferred.resolve(); //Resolve the promise - success
}, function errorCall(respone) {
console.log('error callback register ');
console.log(respone.data);
//$ctrl.selected.item = $ctrl.items[2];
deferred.reject(); //Reject the promise - failure
});
return deferred.promise;
};
请记住将$ q注入您的服务!
在您的控制器中,您可以像这样调用您的服务方法,然后在.then
和.catch
中调整范围变量:
registerService.registerUser(registerInfo)
.then(function() {
$scope.selected.item = $scope.items[1];
//Not sure what your controller looks like, you may be using controllerAs, so this will be a bit different
})
.catch(function() {
$scope.selected.item = $scope.items[2];
});