Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS, $cookieStore inside directive

Tags:

angularjs

I am trying to achieve my goal by using $cookieStore inside my custom directive, but it seems to not working.

Simple as,

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

Then fetch inside controller

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

and that's gave me

undefined.

Any solutions? Is that possible to set cookie inside of directive and acccess it then in controller?

like image 313
nydiann Avatar asked Oct 03 '22 12:10

nydiann


1 Answers

This is example with click event .

Controller

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);
       }
});

directive

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>
like image 112
Nishchit Avatar answered Oct 13 '22 09:10

Nishchit