如何在角动态中设置cookie

时间:2016-01-28 13:55:54

标签: angularjs cookies

我在AngularJS中遇到Cookie问题。我尝试在用户执行操作时创建cookie。我看到了其他示例,但在每个示例中,在创建控制器时会创建静态cookie。 我的HTML代码:

<!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>

这是我的Angular代码:

var app = angular.module("myApp", ['ngCookies']);

app.controller("myCtrl", function($scope, $compile, $http, $cookies) {
    $scope.init = function() {
        var el = '';
        for (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);
    }
});

我的问题在于功能&#34; addToCart&#34;。值未定义。为什么呢?

0 个答案:

没有答案