【问题标题】:angular passing $cookie to on click event in a directive角度将 $cookie 传递给指令中的点击事件
【发布时间】:2016-07-29 20:08:44
【问题描述】:

使用 Angular,我想在单击保存按钮时使用指令将输入的值保存到 cookie。 这是我的代码,我不确定是否应该使用链接函数或控制器指令,但无论如何 $cookie 在单击事件处理程序中当然是未知的。 如何将 $cookie 或 $log 传递给 on Click 函数?

.directive('ndUserSettingCookie', ['$cookies', '$log',function() {
return {
    link: function(scope, el, attrs) {
        scope.savedMsg = ' items by page';
        var setting = [];
        scope.itemsByPage = 18;
        scope.itemsByPage = (typeof setting.itemsByPage !== "undefined")? setting.itemsByPage :scope.itemsByPage;

        el.on('click', function() {                     

            var now = new Date(),
            // this will set the expiration to 12 months
            expireDate = new Date(now.getFullYear()+1, now.getMonth(), now.getDate());

            $cookies.putObject('setting.itemsByPage', scope.itemsByPage, {'expires': expireDate});
            scope.savedMsg = scope.itemsByPage + " items per page saved to your settings!";

            scope.$apply();
        })
    }
}
}])

如果您认为我应该以另一种方式完全这样做,请告诉我。

【问题讨论】:

    标签: angularjs angular-cookies


    【解决方案1】:

    对不起,我只是忘记将它们添加到函数参数中!我的坏!

    这就是它的工作原理:

    .directive('ndUserSettingCookie', ['$cookies', '$log',function($cookies, $log) {
    

    【讨论】:

      猜你喜欢
      • 2019-05-05
      • 1970-01-01
      • 2015-06-10
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      相关资源
      最近更新 更多