Ronan Lamour
Ronan Lamour

Reputation: 1476

Angular.js $cookies : not properly saved/loaded

I am trying to use a simple input that can be retrieved by a cookie automatically.

My angular controller is :

    <script>
    var app = angular.module('mantis', ['ngCookies']);
    app.controller('main', function($scope, $cookies) {

        $scope.nom = '';

        $scope.WriteNom = function () {
            $cookies.put('Nom', $scope.nom);
        };

        $scope.ReadNom = function () {
            $scope.nom = $cookies.get('Nom');
            return $scope.nom;
        };

    });
</script>

In my page, I made a div where I can change the variable "nom" flawlessly. The value should be loaded with ng-init (from cookie) It changes with ng-model And it should be saved with ng-click

<div class="container" ng-app="mantis" ng-controller="main">

    <!-- Assigné à -->
    <div class="col-lg-12">
            <div class="input-group" ng-init="nom=ReadNom()">
                <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                <input id="nom" type="text" class="form-control" name="nom" placeholder="Assigné à (id)" ng-model="nom">
                <span class="input-group-btn">
                    <button class="btn btn-secondary" type="button" ng-click="WriteNom()">Sauvegarder</button>
                </span>
            </div>
    </div>
    (...)

And then, somewhere else, i can use "nom" where I need it by using {{nom}}

It's almost working :

Upvotes: 1

Views: 266

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222722

Remove the return part,

HTML:

  <div class="input-group" ng-init="ReadNom()">

Controller:

$scope.ReadNom = function () {
   $scope.nom = $cookies.get('Nom');          
 };

DEMO

Upvotes: 1

Related Questions