Ronan Lamour Ronan Lamour - 5 days ago 6
AngularJS Question

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 :


  • The value is properly changed when I type in the input box and I can use it

  • The cookie is not changed when I click on the button nor it's loaded when I load the page


Answer

Remove the return part,

HTML:

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

Controller:

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

DEMO

Comments