jquery
and the jquery-cookie
plugin were used to work with jquery-cookie
.
<body ng-app='habr-demo-app'> ... <input type='email' habr-remember-in-cookie='cookie-name-for-email1'/> ... </body>
<h:inputText value="#{mybean.email}" pt:habr-remember-in-cookie="cookie-name-for-email1"/>
(function() { // )();
var app = angular.module('habr-demo-app', []); app.directive('habrRememberInCookie', habrRememberInCookie); function habrRememberInCookie() { function link(scope, element, attrs) { } return { restrict: 'A', link: link }; }
restrict: 'A'
so that the directive could be used only as an attribute.
link
function for each directive on the page. About her well written in the documentation.
link
function itself. In it you need to write the value from the cookie in the input field and configure the change
event handler. When a change
event occurs, write a new value in the cookie.
function link(scope, element, attrs) { if(!element.val()) { var savedValue = $.cookie(attrs.habrRememberInCookie); element.val(savedValue); } element.on('change', function(event) { var newValue = element.val(); $.cookie(attrs.habrRememberInCookie, newValue, {expires: 360}); }); }
$destroy
handler, but in the example above, there is absolutely nothing to do. In general, it looks like this.
element.on('$destroy', function() { console.log('Element deleted'); });
<body ng-app='habr-demo-app'> <input type='email' habr-remember-in-cookie='cookie-name-for-email1'/> </body>
(function() { var app = angular.module('habr-demo-app', []); app.directive('habrRememberInCookie', habrRememberInCookie); function habrRememberInCookie() { function link(scope, element, attrs) { if(!element.val()) { var savedValue = $.cookie(attrs.habrRememberInCookie); element.val(savedValue); } element.on('change', function(event) { var newValue = element.val(); $.cookie(attrs.habrRememberInCookie, newValue, {expires: 360}); }); } return { restrict: 'A', link: link }; } })();
Source: https://habr.com/ru/post/260559/