0

My angularjs webapp contains Login view and Home view.

After logging in, I want my credentials to be saved in order to use them in the future.

For this I saved them in my $rootScope.

Now in my homeController I set them to my $scope this way:

$scope.user = $rootScope.user;
$scope.password = $rootScope.password;

and in my HomeController, the value is properly passed.

When I try to set the value of $scope.user to my DOM using {{using}}, it doesnt seem to work.

Here is the HomeController

'use strict';

angular.module('Home')

.controller('HomeController', ['$scope', '$rootScope',

    function ($scope, $rootScope) {    
        $scope.user = $rootScope.username;
    }]); 

and here is my home view:

<div ng-controller="HomeController as HomeCtrl">
    <h1></h1>
    <p>{{user}}</p>

    <p><a href="#/login">Logout</a></p>
</div>

What am I doing wrong? Sorry for the nooby question and feel free to add more info on how to manage such scenario.

eeadev
  • 3,662
  • 8
  • 47
  • 100
  • 1
    You don't need to `$scope.user = $rootScope.user`. Since `$scope` is a child of `$rootScope`, by inheritance the `user` variable is automatically available in all your `$scope`s. – Jeremy Thille Jan 08 '16 at 15:56
  • 1
    I suggest saving the login data in a service component instead of the scope. So you can inject them everywhere you need them. Look here for an example http://stackoverflow.com/questions/13882077/angularjs-passing-scope-between-routes – dec Jan 08 '16 at 15:56
  • There is no need to copy the values from $rootScope to local $scope, you can just use them in your html sinde $scope's inherit from parent $scope. – Joel Kornbluh Jan 08 '16 at 15:58
  • I disagree. It's better to call $rootScope, because nothing guarantees you that there will never be another variable named "user" for example, between your scope and the $rootScope. – RaidenF Jan 08 '16 at 16:01
  • Also, {{ }} does not set a value to the DOM, it tells angular, to evaluate the expression inside {{ }}, in the current scope, and replace {{ }} with the result (thus it does much more than place a value). Don't mind it too much, just trying to clarify. – RaidenF Jan 08 '16 at 16:04

1 Answers1

0

Try <p>{{HomeCtrl.user}}</p>.

You are using an alias for your controller, and as shown in the documentation, you need to include that alias to reference its scope.

Edit: Since this was accepted, I'll link the related plunkr from the chat.

RaidenF
  • 3,411
  • 4
  • 26
  • 42