5

我试图通过在我的自定义指令中使用 $cookieStore 来实现我的目标,但它似乎不起作用。

很简单,

$cookieStore.put('setMe', 123); ( INSIDE DIRECTIVE )

然后在控制器内部获取

$cookieStore.get('setMe'); ( IN CONTROLLER )

这给了我

undefined.

有什么解决办法吗?是否可以在指令中设置 cookie 并在控制器中访问它?

4

2 回答 2

2

控制器

var App = angular.module('App',['ngCookies']);
App.controller('cookieCtrl',function($scope, $cookieStore){
           var name =  $cookieStore.get("Name");
           console.log(name);
});

指示

App.directive('cookie', function ($cookieStore) {

     return{
         restrict:"E",
         template:"<div>  hello </div>",
         link: function (scope, element, attrs) {
                   $cookieStore.put("Name", 'Nishchit');
         }
     }
});

HTML

  <html ng-app="App">
  <body ng-controller="cookieCtrl">
        <div>
              <cookie> </cookie>
        </div>
  </body>
  </html>

注意 不要忘记在 html 文件中包含 angular-cookies.js 文件,这是由我测试的并且 100% 工作

于 2013-11-07T05:36:12.277 回答
2

这是单击事件的示例。

控制器

var App = angular.module('App',['ngCookies']);
App.controller('cookieCtrl',function($scope, $cookieStore){

       $scope.addCookie = function(){
              $cookieStore.put("Name", 'Nishchit');
       }

       $scope.getCookie = function(){                
             $scope.cookieName =  $cookieStore.get("Name");
             console.log( $scope.cookieName);
       }
});

指示

App.directive('cookie', function ($cookieStore) {

     return{
         restrict:"E",
         scope:{click:"&"},
         template:"<div ng-click='click()'>  hello </div>",
         link: function (scope, element, attrs) {                      
         }
     }
});

HTML

  <html ng-app="App">
  <body ng-controller="cookieCtrl">
        <div>
              <cookie click="addCookie()"> </cookie>  {{cookieName}}

              <button ng-click="getCookie()">get Cookie </button>
        </div>
  </body>
  </html>
于 2013-11-07T09:36:39.617 回答