dongtui4038
dongtui4038
2016-11-15 13:02
浏览 62

将json值存储为angular中的会话

I have a php file which returns json result based from a $http post as seen here:

json result:

now, in my controller below, i want to store 03-1314-00916 or data[0]['student_number'] as a session in angular so i can use it anywhere in any of my controllers. How will i make it.

app.controller('signInCtrl', function($scope, $stateParams, $http) {
  $scope.txtUsername = '';
  $scope.txtPassword = '';

  $scope.signIn = function(){
    $http.post('http://infoyon_login.php',
      {'username' : this.txtUsername, 'password': this.txtPassword})
    .success(function(data){
      if(data[0]['logged'] === true)
      {
        $scope.unable = false;
        console.log(data[0]);
        console.log(data[0]['student_number']);
  here --> someSessionVar = data[0]['student_number'];      
        //window.location = '#/app/dashboard';
      }else{
        //console.log('unable to login');
        $scope.unable = true;

      }
      //console.log(data[0]['logged']);
    })
  }
}) //end controller

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanli3277
    duanli3277 2016-11-15 13:06
    已采纳

    Use HTML5 sessionStorage

    if(data[0]['logged'] === true)
      {
        $scope.unable = false;
        console.log(data[0]);
        console.log(data[0]['student_number']);
        sessionStorage.setItem('student_number', data[0]['student_number']);      
        //window.location = '#/app/dashboard';
      }
    

    To retrieve

       $scope.studentNumber = sessionStorage.getItem('student_number');
    
    点赞 评论
  • dongzi1209
    dongzi1209 2016-11-15 13:13

    You'll want to create a service. If you need it to be present before the page is resolved, you'll want to call that service from within a $route.resolve() function, which you will add to your $routeProvider logic. As for the method, you can use the web storage API as described in the first answer, or if it is a critical part of the application you might consider storing it in $rootScope. Caveat: other commenters may disagree with that option, but there is indeed a time and a place to use $rootScope.

    点赞 评论

相关推荐