使用ng-idle时访问范围变量

时间:2015-06-23 13:53:22

标签: javascript angularjs angularjs-scope ng-idle

ng-idle是一个自定义角度指令,可以找到here,允许您的角度应用程序检查用户是否空闲。

是否有人在使用此指令之前,在编辑指令的属性时是否知道$scope是否存在问题?

这是我的JS:

// include the `ngIdle` module
var app = angular.module('demo', ['ngIdle', 'ui.bootstrap']);

app
.controller('EventsCtrl', function($scope, Idle, $modal) {
    $scope.logIn = function(){
        $scope.loggedIn = true;
        Idle.watch();
    };

    $scope.logOut = function(){
        $scope.loggedIn = false;
        Idle.unwatch();
    };

    $scope.events = [];

    $scope.$on('IdleStart', function() {
        $scope.amIdle = true;
    });

    $scope.$on('IdleWarn', function(e, countdown) {
        // follows after the IdleStart event, but includes a countdown until the user is considered timed out
        // the countdown arg is the number of seconds remaining until then.
        // you can change the title or display a warning dialog from here.
        // you can let them resume their session by calling Idle.watch()
    });

    $scope.$on('IdleTimeout', function() {
        // the user has timed out (meaning idleDuration + timeout has passed without any activity)
        // this is where you'd log them
        $scope.loggedIn = false;
        $scope.amIdle = false;
        Idle.unwatch();
        console.log("Timeout has been reached");
        console.log($scope.loggedIn);
    });

    $scope.$on('IdleEnd', function() {
        // the user has come back from AFK and is doing stuff. if you are warning them, you can use this to hide the dialog
        $scope.amIdle = false;
    });

   /*$scope.$on('Keepalive', function() {
        $scope.amIdle = false;
    });*/

})
.config(function(IdleProvider, KeepaliveProvider) {
    // configure Idle settings
    IdleProvider.idle(5); // in seconds
    IdleProvider.timeout(5); // in seconds
    KeepaliveProvider.interval(1); // in seconds
})

登录/注销内容只是控制loggedIn变量的基本内容,只是与ng-show一起使用,在屏幕上有一个非常基本的日志来测试ng-idle的超时功能。闲置/检测用户是否回来也很好,唯一的问题是使用$scope.$on('IdleTimeout')功能。

程序到达控制台日志,并说两次登录都是false,并且超时已经开始,但应用程序没有相应更新。当注销为false时,应该返回登录屏幕,该屏幕在用户单击注销按钮时有效,但在此实例中不会超时。

1 个答案:

答案 0 :(得分:0)

看来问题是,无论出于何种原因,在更改变量后应用程序都没有更新。这是通过添加

来解决的
$scope.$apply();

在IdleTimeout函数中将两个布尔值设置为false后。