How to pass this variable to the scope?

Asked

Viewed 235 times

-1

(function () {
    angular.module("Hawking").controller('loginController', function ($log, $scope, validateUser) {

        var dataUser = { email: "[email protected]", senha: "123456" };


        validateUser.getUser(dataUser).then(function(data){
            console.log(data); // ok!
            $scope.data = data;
        });


        console.log($scope.data); // undefined 
    })
        .factory('validateUser', function ($http, $q) {
            return {
                getUser: function (userInfo) {
                    var deferred = $q.defer();
                    var status = {
                            id_usuario: null,
                            permission: false
                    };
                     $http.get('/hawkingBE/api/usuarios/').then(function (response) {
                        angular.forEach(response.data, function (value, key) {
                            if (value.email == userInfo.email && value.senha == userInfo.senha) {
                                status = {
                                    id_usuario: value.id_usuario,
                                    permission: true
                                }
                            }
                        });
                    });
                    deferred.resolve(status);
                    return deferred.promise;
                }
            }
        });
})();
  • Have you tried declaring and initializing $scope.data out of function getUser?

1 answer

0

Javascript is asynchronous. That is.. on the javascript runstack the variable $scope.data is not defined. Only then when solving the Factory precedent it will be assigned to the desired variable, that is, there is no way to pass this scope because it is not synchronous.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.