xenish
xenish

Reputation: 1424

How To use Php session variable as Angular Js Data

var app = angular.module('TodoApp', []);

app.controller('TodoCtrl', function($scope){

  $scope.todos = ['test'];

  $scope.done = function(todo){
          var indexOf = $scope.todos.indexOf(todo);
          if (indexOf !== -1) {
              $scope.todos.splice(indexOf, 1);
          }
  };

  $scope.add = function() {
          $scope.todos.push($scope.newTodo);
          $scope.newTodo= '';
  };

});

I am new to angularjs and writing a simple todo list. I want the the data in $scope.todos to be dynamic so whenever a user moves to another page of my site and returns back he will get the same todos he has entered before. I am thinking of using PHP's session varible to store data into it and pass it to the angular app but I don't know how to do it or maybe this logic is not proper.I am new tho this so any new ideas to this would be awesome.

Upvotes: 1

Views: 4340

Answers (1)

at15
at15

Reputation: 139

  1. you can use cookie or local storage to store the user's todo list

  2. when use php session.if you don't want to make an extra ajax call, you have to echo the value in the page.

make the todo list a global var by echo the json in your php file.

var g_todos = <?php echo json_encode($_SESSION['todo'] ?>;

in your controller

if(typeof g_todos === 'object' && g_todos.length){
    $scope.todos = g_todos;
}else{
    $scope.todos = [];
}

I think use cookie or localstorage is better, the second method is quite ugly....

Upvotes: 1

Related Questions