【问题标题】:Personalizing a page using 1 Angular cookie使用 1 个 Angular cookie 个性化页面
【发布时间】:2017-06-20 08:44:07
【问题描述】:

我有一个页面,其中包含可以打开和关闭的信息块。为了知道您希望显示哪些块,我将它们的状态存储在 Angular cookie 中。

HTML:

<block-toggle-btn block-ref="{{ id }}" climbnodes="3" mytarget=".block__content"></block-toggle-btn>

角度指令:

myApp.directive('blockToggleBtn', ['$cookies', function($cookies) {

return {
    restrict: 'E',
    template:'-',
    link: link,
    scope: {
        blockRef: '@',
        mytarget: '@', // target .cssclass
        climbnodes: '=' // Used to climb the dom
    }
};

function link(scope, element, attr) {
    var parent = element.parent();
    for (var i = 0; i < scope.climbnodes; i++) {
        parent = parent.parent();
    }

    var blockRef = scope.blockRef;
    var blockToggleCookie = $cookies.get(blockRef);

    scope.toggleVisibility = function() {

        element.toggleClass('invisible');
        parent.find(scope.mytarget).slideToggle();

        if (element.hasClass('invisible')) {
            element.html('+');
            blockVisible = 'invisible';
            scope.setBlockToggleCookie(blockRef, blockVisible);
        } else {
            element.html('-');
            blockVisible = 'visible';
            scope.setBlockToggleCookie(blockRef, blockVisible);      
        }

    };

    scope.setBlockToggleCookie = function(blockRef, blockVisible) {
        var expireDate = new Date();
        expireDate.setTime(2144232732000);
        $cookies.put(blockRef, blockVisible, {'expires': expireDate});
    };

    // If cookie is set keep block closed
    if (blockToggleCookie == 'invisible') {
        scope.toggleVisibility();
    }

    element.bind('click', function(event) {
        event.preventDefault();            
        scope.toggleVisibility();
    });

}

}]);

目前这工作正常,但它为我显示的每个“块”信息设置一个 cookie。相反,我需要将其全部移动到一个 cookie 中,该 cookie 包含有关要显示哪些块以及要隐藏哪些块的信息。

我知道这听起来像是一个大问题,而且确实如此,但我认为发布整个内容比发布我正在努力解决的每个部分更有用,这样我才能更好地理解并将它们放在一起。目前,我一直在试图弄清楚如何创建一个对象数组以甚至存储在 Angular $cookies.putObject 中。当我尝试将.push() 放入对象数组时,我得到了奇怪的结果。例如,我尝试从点击事件中调用此函数:

        scope.buildCookieObj = function(blockRef, blockVisible) {
            scope.cookieItems.push({blockRef: blockRef, blockVisible: blockVisible});
        };

我知道这不是代码编写服务,我确实尝试过一步一步来,但发现自己迷失了方向。我是 Angular 的新手,知道它何时使用它或插入 JQuery 变得有点不知所措。因此,即使是任何关于采取这一方向的建议也是受欢迎的。

编辑:

我认为我已经取得了一些进展(虽然已经很晚了,所以我还不是 100% 这是有效的,但我认为是这样)。这是设置 cookie 对象的更新代码。现在我只需要检索并迭代它来确定(从 cookie 中)哪些块最初应该设置为关闭。

myApp.directive('blockToggleBtn', ['$cookies', function($cookies) {

var cookieItems = [];

return {
    restrict: 'E',
    template:'-',
    link: link,
    scope: {
        blockRef: '@',
        mytarget: '@', // target .cssclass
        climbnodes: '=' // Used to climb the dom
    }
};

function link(scope, element, attr) {
    var parent = element.parent();
    for (var i = 0; i < scope.climbnodes; i++) {
        parent = parent.parent();
    }



    scope.toggleVisibility = function() {

        element.toggleClass('invisible');
        parent.find(scope.mytarget).slideToggle();

        if (element.hasClass('invisible')) {
            element.html('+');
            blockVisible = 'invisible';
            scope.buildCookieObj(blockRef, blockVisible);
        } else {
            element.html('-');
            blockVisible = 'visible';
            scope.buildCookieObj(blockRef, blockVisible);      
        }
    };

    scope.buildCookieObj = function(blockRef, blockVisible) {
        // If that item already exists remove so we can replace with new visibility setting
        $.each(cookieItems, function(i){
            if(cookieItems[i].blockRef === blockRef) {
                cookieItems.splice(i,1);
                return false;
            }
        });
        cookieItems.push({blockRef: blockRef, blockVisible: blockVisible});
        scope.setBlockToggleCookie(cookieItems);
    };

    scope.setBlockToggleCookie = function(cookieItems) {

        // Maximum value for cookie expiration, i.e. the closest thing to 
        // "never expire" is the year 2038. See:
        // http://stackoverflow.com/questions/532635/javascript-cookie-with-no-expiration-date/532638#532638 and
        // http://stackoverflow.com/questions/34586494/make-cookies-never-expire-with-angularjs
        var expireDate = new Date();
        expireDate.setTime(2144232732000);
        $cookies.putObject('personalization', cookieItems, {'expires': expireDate});
    };

    element.bind('click', function(event) {
        event.preventDefault();
        scope.toggleVisibility();
    });

}
}]);

进一步的进展,实际上相反:

意识到我在设置 cookie 时遇到了一个额外的问题,因为每次重新打开应用程序并关闭和打开块时它都会被覆盖。仍在努力思考这其中的逻辑。如果我将它命名为取决于时间或会话或其他什么,则不确定我将如何检索它以对其进行迭代。

至于 cookie 的检索和设置相应的块以打开或关闭我已经这样做以检索值:

    var personalizationCookie = $cookies.getObject('personalization');
console.log(personalizationCookie);

$.each(personalizationCookie, function(key, value) {
    var blockRef = value.blockRef;
    var blockVisible = value.blockVisible;
    console.log(blockRef, blockVisible);
});

但我还没有弄清楚如何定位块。我想也许只是简单的 Jquery .find() 但我认为 dom 还没有渲染,所以它没有找到任何东西。将其包装在 $( document ).ready() 中我猜是行不通的,因为我们有一个加载屏幕,即使我正在寻找的 dom 元素仍然没有,它也会被“加载”。但这可能是我们的应用程序特有的东西,我必须询问初始构建者。只是想我会在这里更新所有信息。

编辑#2: 所以我想出了一个可行的解决方案,我想在这里“回答”我的问题,但我想出的解决方案仍然需要一些工作。所有的逻辑都在指令中,我知道这不是它应该在的地方。也就是说,我想在这里发布它以防它对任何人有帮助,也因为我正在努力将所有逻辑转移到服务中,并且也欢迎任何方向。 (我已经陷入了服务与工厂的问题,这已经足够令人生畏了,甚至没有开始实际任务!)

myApp.directive('blockToggleBtn', ['$cookies', function($cookies) {
var personalizationCookie = $cookies.getObject('personalization');

return {
    restrict: 'E',
    template:'-',
    link: link,
    scope: {
        blockRef: '@',
        mytarget: '@', // target .cssclass
        climbnodes: '=' // Used to climb the dom
    }
};

function link(scope, element, attr) {

    var parent = element.parent();
    for (var i = 0; i < scope.climbnodes; i++) {
        parent = parent.parent();
    }

    var blockRef = scope.blockRef;

    scope.toggleVisibility = function() {
        element.toggleClass('invisible');
        parent.find(scope.mytarget).slideToggle();

        if (element.hasClass('invisible')) {
            element.html('+');
            blockVisibility = 'invisible';
            scope.buildCookieObj(blockRef, blockVisibility);
        } else {
            element.html('-');
            blockVisibility = 'visible';
            scope.buildCookieObj(blockRef, blockVisibility);
        }
    };

    scope.buildCookieObj = function(blockRef, blockVisibility) {
        // If that item already exists remove so we can replace with new visibility setting
        $.each(personalizationCookie, function(i){
            if(personalizationCookie[i].blockRef === blockRef) {
                personalizationCookie.splice(i,1);
                return false;
            }
        });
        personalizationCookie.push({blockRef: blockRef, blockVisibility: blockVisibility});
        scope.setBlockToggleCookie(personalizationCookie);
    };

    scope.setBlockToggleCookie = function(personalizationCookie) {

        // Maximum value for cookie expiration, i.e. the closest thing to 
        // "never expire" is the year 2038. See:
        // http://stackoverflow.com/questions/532635/javascript-cookie-with-no-expiration-date/532638#532638 and
        // http://stackoverflow.com/questions/34586494/make-cookies-never-expire-with-angularjs
        var expireDate = new Date();
        expireDate.setTime(2144232732000);
        $cookies.putObject('personalization', personalizationCookie, {'expires': expireDate});
        var personalizationCookie = $cookies.getObject('personalization');
    };

    // Check to see if there's a cookie for this element's block
    // If yes, then toggle minus to plus and hide the block content the button refers to
    $.each(personalizationCookie, function(key, value) {
        if ((value.blockRef == scope.blockRef) && (value.blockVisibility == 'invisible')) {
            parent.find(scope.mytarget).hide();
            element.html('+').addClass('invisible');
        }
    });

    element.bind('click', function(event) {
        event.preventDefault();
        scope.toggleVisibility();
    });

}

}]);

【问题讨论】:

    标签: javascript jquery angularjs cookies


    【解决方案1】:

    以防万一有人好奇,我最终弄清楚了这一点,并且与上面几乎相同,我只是将任何与 DOM 无关的东西移到了服务中:

    tsApp.service('personalizationCookieService', ['$cookies', function($cookies) {
    if ($cookies.getObject('personalization')) {
        var personalizationCookie = $cookies.getObject('personalization');
    } else {
        var personalizationCookie = [];
    }
    
    function setBlockToggleCookie(personalizationCookie) {
        // Maximum value for cookie expiration, i.e. the closest thing to
        // "never expire" is the year 2038. See:
        // http://stackoverflow.com/questions/532635/javascript-cookie-with-no-expiration-date/532638#532638 and
        // http://stackoverflow.com/questions/34586494/make-cookies-never-expire-with-angularjs
        var expireDate = new Date();
        expireDate.setTime(2144232732000);
        $cookies.putObject('personalization', personalizationCookie, {
            'expires': expireDate
        });
    }
    
    return {
    
        buildCookieObj: function(blockRef, blockVisibility) {
            // If that item already exists remove so we can replace with new visibility setting
            $.each(personalizationCookie, function(i) {
                if (personalizationCookie[i].blockRef === blockRef) {
                    personalizationCookie.splice(i, 1);
                    return false;
                }
            });
            personalizationCookie.push({
                blockRef: blockRef,
                blockVisibility: blockVisibility
            });
            setBlockToggleCookie(personalizationCookie);
        }
    
    };
    
    }]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      • 1970-01-01
      • 2017-08-29
      相关资源
      最近更新 更多