如何在角度js文件中使用cookie?

时间:2015-01-16 11:25:02

标签: javascript jquery angularjs angularjs-directive angularjs-scope

我正在尝试在angular中使用cookie。我已经在javascript中使用会话和本地存储。你能不能告诉我如何使用有角度的cookie我将得到" undefined"使用angular时出错。我学习教程 https://github.com/ivpusic/angular-cookie

这是我的代码 http://goo.gl/NTmqNA

<!doctype html>
<html ng-app>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
        <script src="app.js"></script>
        <script src="cookies.js"></script>

  </head>
  <body ng-app="app">
    <div ng-controller="cont">

    </div>
  </body>
  <script>
     var app= angular.module('app',['ipCookie'])
     function cont($scope,ipCookie){
         ipCookie("test", "testvalue
         console.log(ipCookie("test"))
     }
  </script>
</html>

1 个答案:

答案 0 :(得分:4)

将对cookies.js的引用替换为https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular-cookies.js。然后你的脚本看起来像这样:

var app = angular.module('app', ['ngCookies'])

app.controller('cont', ['$cookies', function($cookies) {
    // Retrieving a cookie
    var favoriteCookie = $cookies.myFavorite;
    // Setting a cookie
    $cookies.myFavorite = 'oatmeal';
}]);

编辑:或者,如果你想坚持使用ipCookie,这样的事情应该有效:

<!doctype html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
        <script src="app.js"></script>
        <script src="cookies.js"></script>

    </head>

    <body ng-app="app">
        <div ng-controller="cont">

        </div>

        <script>
            var app= angular.module('app',['ipCookie'])

            app.controller("cont", function($scope,ipCookie){
                ipCookie("test", "testvalue");
                console.log(ipCookie("test"))
            });
        </script>
    </body>

</html>