2

Code was working fine till I decided to move my login and registration form onto its own partial, now after i login, it does redirect to partials/dashboard.html but my user object data is not accessible anymore. I have console.logged in my script.js to check, the object does get consoled but then I cant access it on my dashboard.html

Index.html

<!DOCTYPE html>
<html ng-app='fullmean_app'> <!-- NAME & Load NG app -->
<head>
    <title>Discussion Board</title>
    <!-- require angular -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"/></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular-route.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.10/ngStorage.min.js"></script>
    <script src="/js/user_script.js"></script>
    <script src="/js/topic_script.js"></script>
</head>
<body> <!--  !! LOAD CONTROLLER ** CHECK NAME ** !! -->
    <div ng-view="">

    </div>
</body>
</html>

Dashboard.html

    <div ng-controller="loginController">

      <a href="#/dashboard">Dashboard</a> | <a href="#/topics">Topics</a> | <a href="#/users">Users</a>
    <h4>Welcome {{users.name}}</h4>
      {{$storage.user.name}}
      {{user.name}}
      {{$storage.user.name}}

      <div ng-repeat="user in users"><h4>{user.name}}</h4></div>
      <!--  Have tried multiple combinations to access the data ,, but none working -->
      <form>
        <input type='submit' value='Logout' ng-click='logout()'>
    </form>
</div>
<div ng-controller="topicController">
    <form>
        <label>Add a new Topic</label><br>
        <label>Topic</label><br>
            <input type='text' name="topic" ng-model='new_topic.topic'><br>
            <label>Description</label><br>
            <textarea name="description" ng-model="new_topic.description">Description</textarea><br>
            <label>Category</label><br>
            <select name="category" ng-model="new_topic.category">
                <option value="HTML">HTML</option>
                <option value="Javascript">Javascript</option>
                <option value="Ruby">Ruby</option>
                <option value="Python">Pyhton</option>
                <option value="Php">Php</option>
                <option value="iOs">iOs</option>
            </select><br>
            <input type='submit' value='Submit' ng-click='addTopic($storage.user._id)'>
    </form>
</div>

login.html

<div ng-controller='userController'>
        <h3>Register</h3>
            <form>
                <label>Name</label><br>
                <input type='text' name="name" ng-model='new_user.name'><br>
                <label>Email</label><br>
                <input type='email' name="email" ng-model='new_user.email'><br>
                <label>Password</label><br>
                <input type='password' name="password" ng-model='new_user.password'><br>
                <input type='submit' value='Create' ng-click='addUser()'>
            </form>
</div>
<div ng-controller='loginController'>
             <h3>Login</h3>
            <form>
                <label>Email</label>
                <input type='email' name="email" ng-model='user.email'><br>
                <label>Password</label><br>
                <input type='password' name="password" ng-model='user.password'><br>
                <input type='submit' value='Login' ng-click='getUser()'>
            </form>
</div> 

Script.js

var myapp = angular.module('fullmean_app', ['ngRoute','ngStorage']);
    myapp.config(function ($routeProvider) {
        $routeProvider
        .when('/',{     
                templateUrl: 'partials/login.html'
            })
            .when('/dashboard',{
                templateUrl: 'partials/dashboard.html'
            })
            .when('/topics',{
                templateUrl: 'partials/topic.html'
            })
            .when('/users',{
                templateUrl: 'partials/user.html'
            })
            .otherwise({
              redirectTo: '/'
            });
        });

    myapp.factory('userFactory', function($http, $location, $localStorage, $sessionStorage) {
        var factory = {};
        console.log("Im at the user factory")
        factory.addUser = function(info, callback) {
            $http.post('/create', info).success(function(output){
                callback(output);
            })
          }
          return factory;
    });

    myapp.factory('topicFactory', function($http, $location, $localStorage, $sessionStorage) {

         var factory = {};

        factory.addTopic = function(info, callback) {
             console.log("Im at the topic factory")
            $http.post('/create_topic', info).success(function(output){
                callback(output);
            })
          }
          return factory;
    });

    myapp.factory('loginFactory', function($http, $location, $localStorage, $sessionStorage) {

        var factory = {};
        factory.getUser = function(info, callback) {
            $http.post('/login', info).success(function(output){
                callback(output);
            })
          }
          return factory;
    });



    myapp.controller('userController', function($scope, userFactory, topicFactory, $localStorage, $sessionStorage, $location) {

        console.log("Entered User Controller");

        $scope.addUser = function() {      
        console.log("Im at the controller") 
            var user_repack ={
                name: $scope.new_user.name,
                email: $scope.new_user.email,
                password: $scope.new_user.password,
                created_at: new Date()
            }
            userFactory.addUser(user_repack, function(data) {
                     $scope.users = data;
                      $scope.new_user = {};    
            });
        }
    })

    myapp.controller('loginController', function($scope, loginFactory, $localStorage, $sessionStorage, $location) {

            $scope.getUser = function(){
            console.log("Entered getUser controller")
            var user_repack = {
                email: $scope.user.email,
                password: $scope.user.password
            }
            loginFactory.getUser(user_repack, function(data){
                $location.path('/dashboard')
                $scope.users = data
                console.log($scope.users, "$scope.users")
                $scope.$storage = $localStorage.$default({
                  user: data
                });
               console.log($scope.$storage.user.name);
            });
        }

        $scope.logout = function(){
            console.log("Logged out");
            $localStorage.$reset();
            $location.path('/')
        }
    })

    myapp.controller('topicController', function($scope, topicFactory, $localStorage, $sessionStorage) {
            $scope.addTopic = function(input){
            console.log("Hey im here");
            console.log(input, "Input Console");
            var topic_repack = {
                topic: $scope.new_topic.topic,
                description: $scope.new_topic.description,
                category: $scope.new_topic.category,
                user_id: input
            }
            console.log(topic_repack);
            topicFactory.addTopic(topic_repack, function(data){
                $scope.topics = data;
                $scope.new_topic = {}; 
            });
        }
     })

The Server side code is working fine, as user registration is working, login form does grab the user object. The add topic was working fine upto this point as well.

This is what my Chrome Console is printing

Im sure it will be something very small but just cant see it. Appreciate the help in advance .. thanks

have updated the code, segregated the controllers to avoid confusion and still nothing, whats wird is if you see ive added a

console.log($scope.$storage.user.name);

after setting the data in my local storage inside my loginController. it actually does console.log the name field in my Chrome Javascript Console. But is not printing in dashboard.html

simba777
  • 71
  • 14

2 Answers2

1

Fixed it by setting the data in $rootScope instead of $scope.

loginController

myapp.controller('loginController', function($scope, $rootScope, loginFactory, $localStorage, $sessionStorage, $location) {

            $scope.getUser = function(){
            console.log("Entered getUser controller")
            var user_repack = {
                email: $scope.user.email,
                password: $scope.user.password
            }
            loginFactory.getUser(user_repack, function(data){
                $location.path('/dashboard')
                $rootScope.users = data
                console.log($rootScope.users, "rootScope")
            });
        }

        $scope.logout = function(){
            console.log("Logged out");
            for (var i in $rootScope) {
                if (i.substring(0,1) !== '$') {
                    delete $rootScope[i];
                }
            }
            $location.path('/')
        }
    })

The logout function was made with the help of this previously answered Q How to reset $rootScope?

Community
  • 1
  • 1
simba777
  • 71
  • 14
0

login page and dashboard page uses the same controller but different instances. You need to store the logged in user object in a service or local storage and retrieve it when you need to.

I'd suggest you not to use the same controller as it might confused you, and also from separation of duty perspective.

sdfacre
  • 1,273
  • 7
  • 7
  • I did what you suggested, have edited the Original post with the updated code. It is a better practice to separate the controllers i agree, Thanks. But still no changes. . same problem. – simba777 Feb 03 '16 at 04:06
  • you must use the service wrongly. put it in a plunker and I will let you know. – sdfacre Feb 03 '16 at 04:10
  • https://github.com/anirudhh1988/angular_discussion_board have uploaded on github, is that helpfull? ive made the repo public – simba777 Feb 03 '16 at 04:25