update variable in another controller in AngularJS

时间:2015-07-28 16:18:24

标签: javascript jquery angularjs twitter-bootstrap

okay, so I am building a web-app using angular.js. I have started to implement user authentication.

I did this with it's own controller:

app.controller("userControl", ["$http", "share", function($http, share){
this.login = {};
var user = this;
this.doLogin = function(){
    this.login.fn = "login";
    $http.post('classes/main.php', user.login).success(function(data){
        console.log(data.Error);
        if(data.Error == undefined){
            alert("Success");
            share.user = data;
            window.location.href = "#memberHome";
        }
    }); 
}
}]);

and I have a member's page with it's own controller:

HTML:

<div id="memberHome" data-role="page" ng-controller="member-Ctrl as member">
    <nav class="navbar navbar-inverse">
        <div class="container-fluid">
            <div class="navbar-header">
                <p class="navbar-brand" href="#">Calendar</p>
            </div>
            <ul class="nav navbar-nav navbar-left">
                <li><a href="#">Overview</a></li>
                <li><a href="#">Friends</a></li>
            </ul>

            <ul class="nav navbar-nav navbar-right">
                <li><a href="#"><span class="glyphicon glyphicon-user"></span> Logged in as: {{member.user.forename + " " + member.user.surname}}</a></li>
                <li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Log Out</a></li>
            </ul>
        </div>  
    </nav>
    <div data-role="content">
        <calendar selected="day"></calendar>

    </div>
</div>

javascript:

app.controller("member-Ctrl", ["share", function(share){
this.user=share.user;

}]);

I need the User controller to tell the member controller the details of the new user.

I googled this and looked at the answers of a similar question, which led me to This

and i created a service as shown in the video:

app.service("share", function(){
    this.user = {}

});

Now whenever i login and get redirected to the memberHome page, it tells me Logged in as:

Can anybody see why this might be?

I am very new to Angular, and am learning, just about, everything when I need it.

I should probably say that i am using jQuery Mobile (for a multi-page document) and Bootstrap 3

1 个答案:

答案 0 :(得分:12)

You can use a service to share information between controllers or use the $rootScope

var app = angular.module('mymodule',[]);
app.controller('Controller1', ['$scope','$rootScope',
  function($scope, $rootScope) {
    $rootScope.showImages = true;
}]);

app.controller('Controller2', ['$scope','$rootScope',
  function($scope, $rootScope) {
    $rootScope.showImages = false;
}]);

And in the template:

<div ng-controller="Controller1">
    <div class="images" ng-show="$root.showImages"></div>
</div>