Angularjs how to change text in a view from a different view's controller

532 Views Asked by At

I am missing something very elementary....

I have three views created in angularJS: a header, a body and a footer. I want to change the text in the header from login to logout upon successful login, also from logout to login when the user is logged out.

My files/code:

index.php:

    <div ui-view="header"></div>
    <div ui-view="main"></div>
    <div ui-view="footer"></div>

header.page.html ( I think I want ng-bind or {{some var}} here )

    <li><a href="#login" >Login</a></li>

login.component.js (not sure how to get a value to the header.page.html)

    login(){
        var user = {
            company: this.company,
            username: this.username,
            password: this.password
        };
        var me = this;
        this.$auth
            .login(user)
            .then(function (response) {
                me.$auth.setToken(response.data);


// CHANGE LOGIN TO LOGOUT IN HEADER



                me.$state.go('app.dashboard');
            })
            .catch(function (response) {
                console.log("error response", response);
            })
    };

And the logout function (Not sure how to get a value to header.page.html)

function dashboardController($state, $scope, $auth){
$scope.isAuthenticated = function () {
    return $auth.isAuthenticated();
};
document.title = "Dashboard";
$scope.logout = function () {
    $auth.logout();

    //change Logout To Login text in header

    $state.go('app.home');
};

}

2

There are 2 best solutions below

2
Rodrigo Branas On BEST ANSWER

You could use $broadcast, $emit and $on. More details in: https://docs.angularjs.org/api/ng/type/$rootScope.Scope

Other solution would be using $rootScope, but take care about poluting it.

As far as it regards to some application related information, like user information, honestly, a solution based on $rootScope is not totally wrong.

You should definately avoid $rootScope for feature specific information.

I would study more about using broadcast in order to decide.

1
Daniel Kuta On

If you want only change text in header form login you can get access to your

<li><a id="login" href="#login" >Login</a></li>

like this: document.getElementById("login") and set new text or you can use service. Service you should inejct to login and header controller.