11

对角度非常陌生;我确定我错过了一些非常明显的东西。

我的页面上有一个登录表单。我想要发生的是在用户成功登录后隐藏表单。

我的整个页面使用一个控制器。

这是HTML;尽管在同一个控制器中实际上还有其他内容,但我已经删除了除登录字段之外的所有内容:

<div ng-app="Localizer" ng-controller="StoreListCtrl" ng-init="my_occasion = ''">
    <div ng-show="user_signed_in===false">

        <div class="row"><h1>Have an account?</h1>
            <p>Sign in to quickly access addresses saved to your account</p></div>
            <div class="row">
                <div class="data">
                    <input type="username" ng-model="username" name="username" data-placeholder="Username" />
                </div>
                <div class="data">
                    <input type="password" ng-model="password" name="password" data-placeholder="Password" />
                </div>
                <div class="data"> 
                    <div class="syo-acctSignBtn yButtonTemplate" ng-click="login_user()">Sign In<div class="btnArrow iconPosition"></div></div>
                </div>
        </div>
    </div>
</div>

当用户单击登录按钮时,一个名为的函数login_user()运行。这行得通;如果我手动刷新页面,我确实看到我已经登录并且需要隐藏的 div 被隐藏了。但是如果不刷新页面,div 仍然可见,即使它所依赖的变量 ( user_signed_in) 确实得到了更新。

这是login_user我的控制器中的功能;我去掉了很多东西,包括前端字段验证:

$scope.login_user = function() {
    $.post('/site/ajax/login/do_login', {'username': $scope.username, 'password': $scope.password}, function(data) {
        if (data.success) {
                    $window.user_state.status = $window.user_status_key.STATE_SIGNED_IN;
            $scope.user_signed_in = $window.user_state.status == $window.user_status_key.STATE_SIGNED_IN;
            console.log("user status: " + $window.user_state.status );
                    console.log("user status key: " + $window.user_status_key.STATE_SIGNED_IN);
                    console.log("scope.user_signed_in: " + $scope.user_signed_in);
        } else {
            Modal({
                title: "Could not Login",
                text: data['errMsg'],
                yellow_button: {btn_text: "OK"}
            });
        }
    });

};

这是console.log行的结果:

用户状态:已登录用户状态密钥:已登录 scope.user_signed_in:true

由于user_signed_in不等于false,我希望<div ng-show="user_signed_in===false">div 内显示的所有表单内容都隐藏起来。但它没有(再次,除非我手动刷新页面。)我错过了什么?

4

2 回答 2

23

问题是您user_logged_in在 Angular 上下文之外更新了变量 ( ),因此 Angular 对此一无所知(例如,直到您刷新页面)。

您应该将回调的主体包装在$scope.$apply()

$apply() 用于从 Angular 框架外部执行 Angular 表达式。(例如来自浏览器 DOM 事件、setTimeout、XHR第三方库)。因为我们正在调用 Angular 框架,所以我们需要执行适当的异常处理范围生命周期,执行 watch。

(强调我的)


顺便说一句,如果您使用该服务执行您的请求,您将不会遇到同样的问题$http,因为它是 Angular-context-aware。

于 2014-03-13T20:30:55.920 回答
0
function ShowLoading($scope) {
$scope.loading = true;
setTimeout(function () {
   $scope.$apply(function(){
            $scope.loading = false;
   });
 }, 2000);
}
于 2017-02-16T12:10:39.860 回答