ng-repeat将某些值保存为cookie

时间:2016-05-14 11:40:10

标签: javascript angularjs cookies

我使用$ http获取JSON数据,我使用ng-repeat(表格格式)显示它我想为每个表格数据添加一个按钮,所以点击该值将保存为cookie。请帮帮我

1 个答案:

答案 0 :(得分:2)

查看:

<script src="~/Scripts/angular.js"></script>
<script type="text/javascript">

    function createCookie(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    }

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

    myApp.controller('controller', function ($scope, $http, $compile) {

        $scope.employees = [{ "name": "Employee1", "surname": "Surname1" },
                            { "name": "Employee2", "surname": "Surname2" },
                            { "name": "Employee3", "surname": "Surname3" },
                            { "name": "Employee4", "surname": "Surname4" }];

        $scope.AddCookie = function (employee) {

            debugger;
            var cookie = employee.name + " " + employee.surname;
            createCookie("Employee", cookie, 1);

        }
    });

</script>

<div ng-app="myApp" ng-controller="controller">
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Surname</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="e in employees">
                <td>{{e.name}}</td>
                <td>{{e.surname}}</td>
                <td><input type="button" value="Add Cooke" ng-click="AddCookie(e)"/></td>
            </tr>
        </tbody>
    </table>
</div>

以下是您的Cookie:

cookie in google chrome