angularjs TypeError: Cannot read property of undefined

1.6k views Asked by At

Hey guys I'm having some issues with the following code as it is producing a TypeError even though I thing I've made sure that all the appropriate directives are accounte for

.controller('loginCtrl', ['$scope', 'loginService', '$location',
  function($scope, loginService, $location) {
    $scope.check_credentials = function(loginData) {
      $params = $.param({
        "pass": loginData.password,
        "email": loginData.email,
      })
      loginService.login($params).then(function(data) {

        if (globalData.users[0].userId.length > 0) {

          $location.path('/welcome');
        }

      });
    }
  }
])


.factory('loginService', ['$http', '$rootScope', 'sessionService',
    function($http, $rootScope, $location, sessionService) {
      return {
        login: function($params) {
          return $http({
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
            url: 'login_process.php',
            method: "POST",
            data: $params,
          }).success(function(data) {
            globalData = data;
            sessionService.set('userId', globalData.userId);
          });
        },

        logout: function() {
          sessionService.destroy('user');
        }
      }
    }
  ])
  .factory('sessionService', ['$http', '$rootScope',
    function($http, $rootScope, $location) {
      return {
        set: function(key, value) {
          return sessionStorage.setItem(key, value);
        },

        get: function(key) {
          return sessionStorage.getItem(key);
        },

        destroy: function(key) {
          return sessionStorage.removeItem(key);
        }
      }
    }
  ])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<div class="col-lg-6" ng-controller="loginCtrl">
  <div class="container-fluid">
    <h2 class="form-signin-heading">Please sign in</h2>
    <form>
      <label for="inputEmail" class="sr-only">Email address</label>
      <input type="email" class="form-control" placeholder="Email address" required autofocus ng-model="loginData.email">
      <label for="inputPassword" class="sr-only">Password</label>
      <input type="password" class="form-control" placeholder="Password" ng-model="loginData.password" required>
      <div class="checkbox">
        <label>
          <input type="checkbox" value="remember-me">Remember me
        </label>
      </div>
      <button class="btn btn-lg btn-primary btn-block" ng-click="check_credentials(loginData)">Sign in</button>
      <span id="message"></span>
    </form>
  </div>
</div>

The code should create a variable in local session storage and assign a value to it.

0

There are 0 answers