angularjs - How to set cookies in angular dynamic -
i have problem cookies in angularjs. tried create cookie when user did action. saw others examples, in each example cookie created statical when controller created. html code:
<!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href="style/bootstrap-3.3.6.min .css"> <link rel="stylesheet" type="text/css" href="style/style.css"> </head> <body ng-app="myapp"> <div class="container-fluid" ng-controller="myctrl"> <div class="row" id="all_products" data-ng-init="init()"> </div> </div> <script type="text/javascript" src="script/angular-1.4.9.min.js"></script> <script type="text/javascript" src="script/angular-cookies-1.4.9.min.js"></script> <script type="text/javascript" src="script/data.js"></script> <script type="text/javascript" src="script/app.js"></script> </body> </html>
and angular code:
var app = angular.module("myapp", ['ngcookies']); app.controller("myctrl", function($scope, $compile, $http, $cookies) { $scope.init = function() { var el = ''; (var i=0; i<data.length; i++){ el += '<div class="preview col-xs-12 col-sm-6 col-md-4 col-lg-4">'; el += '<div class="preview-body">'; el += '<div class="left col-xs-8 col-sm-8 col-md-8 col-lg-8">'; el += '<button class="btn btn-primary preview_buy" ng-click="addtocart('+i+')">buy</button>'; el += '</div>'; el += '<div class="right col-xs-4 col-sm-4 col-md-4 col-lg-4">'; el += '<a href="product.html?id='+i+'"><img src="'+data[i].images[0]+'"/></a>'; el += '</div>'; el += '</div>'; el += '</div>'; } var element = angular.element(document.queryselector('#all_products')); var generated = element.html(el); $compile(generated.contents())($scope); } $scope.addtocart = function(id) { $cookies.put('checked', id); var value = $cookies.get("checked"); console.log(value); } });
my problem in function "addtocart". value undefined. why?
Comments
Post a Comment