Eddy Freeman
Eddy Freeman

Reputation: 3309

Issues with AngularJS Controller

I have the following setup in my html file:

<body>
    <nav ng-controller="loginCtrl">
        <div>
            <li>Apple</li>
            <li>Mango</li>
            <li>{{user}}</li>
        </div>
    </nav>

    <div ui-view></div>

</body>

I have a navigation menu and the ui-view that displays different pages.

I also have a controller, loginCtrl, with a scope variable called $scope.user. This controller is also called in the UI-state router for the login.html file as well so that the login form can use its methods.

When a user logs in, I want to show his name in the navigation menu using the {{user}} above. The navigation menu as you can see is visible (static) regardless of other partial pages that will be loaded in the ui-view.

At the moment, it is not working and I don't know why.

My understanding is that the login form in the login.html and the navigation menu are in different files so that may be they are using the same controller (under the same module) yet may be operating in different scopes/environments (am not really sure about that).

That is why I update the value of $scope.user but it doesn't appear in the navigation menu.

Why is it not working and how can I achieve my functionality?

Upvotes: 2

Views: 78

Answers (2)

Micka&#235;l R.
Micka&#235;l R.

Reputation: 344

I'm wondering if it's necessary to cal your LoginController for your ui-view and a sibling element, when you could load it on a parent element

Anyway, you have several solutions to make the two-way binding work:

  • @vp_arth solution is really great, usually used this to share data between controllers
  • Move your ng-controller attribute to a common parent element, and if needed, declare another controller for your login.html, that will be a child of your LoginController. Then use an object instead of a variable in your parent scope:

$scope.user = {};

and then fill it in your child scope like this: $scope.user.name = ...

Even if you're using the same controller as parent AND child scope, you should make this work with something like this: $scope.user = $scope.user ? $scope.user : {}; instead of $scope.user = {};

(if it's not clear I can make a comparative fiddle to show you)

This wiki really helped me when I had issues like yours: https://github.com/angular/angular.js/wiki/Understanding-Scopes

Upvotes: 0

vp_arth
vp_arth

Reputation: 14992

Using a singleton service to share same UserData object:

app.service('UserData', function(){return {name: 'default'};});
app.controller('LoginController', function($scope, UserData){
    $scope.user = UserData;
});

Now, all controller instances have access to same UserData object.
When user.name has changed, all controllers can see it.

Upvotes: 2

Related Questions