AngularJS,$ cookieStore inside指令

时间:2013-11-06 23:42:39

标签: angularjs

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

简单,

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

然后获取内部控制器

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

那就是给了我

undefined.

任何解决方案?是否可以在指令中设置cookie并在控制器中处理它?<​​/ p>

2 个答案:

答案 0 :(得分: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%正常工作

答案 1 :(得分: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>