如何从AngularJS指令定义中访问$ cookies服务

时间:2013-05-30 20:41:26

标签: cookies angularjs angularjs-directive

我有以下内容:

angular.module("thingy", ["ngCookies"]).directive("welcome", function() {
    return {
        link: function($scope, el, attr, ctrl) {
                        (if $cookies.something) {
                            // conditional cookie logic
                        }
        },
        templateUrl: "assets/html/_welcome.html"
    };
})

如何从该链接功能中读取或写入cookie?

1 个答案:

答案 0 :(得分:5)

你需要注射它。请参阅this文档。

angular.module("thingy", ["ngCookies"]).directive("welcome", ['$cookies', function($cookies) {
  return {
    link: function($scope, el, attr, ctrl) {
      if ($cookies.something) {
        // conditional cookie logic
      }
    },
    templateUrl: "assets/html/_welcome.html"
  };
}])