Sanjay Achar
Sanjay Achar

Reputation: 408

ng-repeat save certain value as cookie

I am fetching JSON data using $http, and I am displaying it using ng-repeat (table format) I want to add a button to every table data, so on click that value will be saved as a cookie. Please help me out here

Upvotes: 2

Views: 164

Answers (1)

Denys Wessels
Denys Wessels

Reputation: 17049

View:

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

And here is your cookie:

cookie in google chrome

Upvotes: 2

Related Questions