将变量从成功调用通过控制器传递到视图

时间:2017-08-09 13:45:29

标签: angularjs service scope call

在我的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];的这种方法显然不起作用..我该怎么做?我不知道我需要异步执行此操作。

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];
   });