为什么$ scope不在视图上?

时间:2016-05-31 20:19:02

标签: javascript angularjs scope

我有下一个控制器:

.controller('LogInController', function(logInFactory, $scope, $location, $state){
     $scope.logIn = function() {
            $scope.dataLoading = true;
            logInFactory.logIn($scope.email, $scope.password, function (response) {
                if (response.success) {
                    $scope.userName = response.userName;
                    console.log('userName', $scope.userName);
                    logInFactory.setCredentials($scope.email, $scope.password);
                    $location.path('/users');
                } else {
                    $scope.dataLoading = false;
                }
            });
        };
    $scope.clearCredentials = function(){
        $state.go('login');
        logInFactory.clearCredentials();
    };    
});//End controller

我想在这个视图中使用它:

<div class="header" ng-controller = 'LogInController'>
    <img src= "logo.jpg">
    {{userName}}
    <button ng-click = 'clearCredentials()'> Cerrar sesión</button>
</div>

但是在视图中没有显示userName,但是当我在控制器上打印它时,它正确显示。调用logIn()函数后会显示该视图。

这是我工厂的logIn功能:

var logIn = function(email, password, callback){
            var URL;

            if(ENV.mocksEnable){
                URL = ENV.apiMock + ENV.logInMock;
                return (
                    $timeout(function () {
                        var response;
                        getUser()
                        .then(function (user) {
                            console.log('USER', user);
                            if (user !== null) {
                                response = { success: true, userName: user.userName};
                            } else {
                                response = { success: false, message: 'Username or password is incorrect' };
                            }
                            callback(response);
                        });
                    }, 1000)
                );
            }else{
                URL = ENV.apiURL + ENV.logIn;
                return (
                    $http.post(URL, {email : email, password : password})
                    .then(function onFulfilled(response){
                        var data = response.data;
                        userName = data.username;
                        userEmail = data.email;
                        userId  = data.id;
                        profiles = data.profiles;
                        callback(response);
                        return data;
                    })
                    .catch(function onRejected(errorResponse){
                        console.log('Error in logInFactory');
                        console.log('Status: ', errorResponse.status);
                        callback(errorResponse);
                        return errorResponse;
                    })
                );
            }
        };//End login

我在此视图中触发logIn()函数

<form ng-submit = 'logIn()'>
  <h1>Log In</h1>       
  Correo electrónico:
  <input type="email" ng-model='email' required><br>
  Contraseña
  <input type="password" ng-model='password' required><br>
  <input type="submit" value="Log in">
</form>

当我触发logIn()时,我应该转到那个标题并显示userName。

5 个答案:

答案 0 :(得分:0)

为什么要触发clearCredentials()?而根据此代码,您应该触发login()

答案 1 :(得分:0)

logIn()函数的结果可能超出了Angular范围。

尝试将logIn函数的结果包装到$ timeout(调用$ apply,强制Angular刷新控制器范围的方法):

$timeout(function() {
    if (response.success) {
       $scope.userName = response.userName;
       console.log('userName', $scope.userName);
       logInFactory.setCredentials($scope.email, $scope.password);
       $location.path('/users');
    } else {
       $scope.dataLoading = false;
    }
});

不要忘记在控制器中注入依赖项$ timeout。

答案 2 :(得分:0)

在logIn方法成功的范围内有$ scope.userName。在发生这种情况之前它将无法使用。

如果你将$ scope.userName放在方法之外并将其设置为某个东西,它就会出现。

.controller('LogInController', function(logInFactory, $scope, $location, $state) {
  $scope.userName = 'test name';
  $scope.logIn = function() { ...

类似的东西。

答案 3 :(得分:0)

我们没有您的工厂代码,但这条线对我来说很奇怪:

logInFactory.logIn($scope.email, $scope.password, function (response) { ..; } )

所以你将功能传递给工厂,并不是工厂将数据返回给控制器。

它应该是这样的:

logInFactory.logIn($scope.email, $scope.password).then(function (response) { ..; } );

编辑: 您必须从工厂中删除回调函数,并使工厂返回数据并处理此类logInFactory.logIn($scope.email, $scope.password).then(function (response) { ..; } );之类的数据。

您已登录控制台,但工厂和控制器之间未共享$ scope,因此工厂中的回调会编辑$scope.userName,但控制器无法进行此更改。

答案 4 :(得分:0)

我的问题是我希望从控制器获取数据到两个不同的视图。当我从LogIn视图转到我的标题视图时,控制器刷新其数据。所以,我必须在我的工厂创建:

var getUserName =  function() {
            return userName;
};

在控制器中

$scope.userName = logInFactory.getUserName(); 

现在我的userName在工厂中存在。