简体   繁体   中英

ng-show not updating

I'm trying to get a broadcast to switch which view is currently being displayed, but when I change the controller's model, the ng-show doensn't change to reflect the new state.

I'm using $rootScope.$broadcast("registerFormShow", username, password) to tell the RegisterForm controller that I want it to be visible. It has a variable register.active that I have in the ng-show, but it doesn't seem to apply the change. I've tried calling $scope.$apply() from within the $on callback, but angular throws an exception saying that $apply is already in progress . Any ideas why this is happening?

Here's some of my code:

app.controller("LoginController", ["$http", "$rootScope", function($http, $rootScope){

    this.openRegister = function(username, password){
        $rootScope.$apply(function(){
            $rootScope.$broadcast("register", username, password);
        });
        this.loggedIn = true;
        console.log("register even sent");
    }

}]);
app.controller("RegisterController", ["$http", "$scope", function($http, $scope){
    this.active = false;
    $scope.$on("register", function(username, password){
        this.active = true;
    }
}]);

Html:

<div ng-controller="RegisterController as register" ng-show="register.active" class="cover">
        <div class="form register-form" ng-class="{indeterminate: register.indeterminate}">

            <input type="text" name="username" required="" ng-model="username" />
            <input type="password" required="" ng-model="password" />
            <button ng-click="register.register(username, password)">Register</button>
        </div>
    </div>

Here's a link to a demo demonstrating this problem: http://jsfiddle.net/7LLa7zot/1/

I would try

 this.active = false;
 var _this = this;
    $scope.$on("register", function(username, password){
        _this.active = true;
    }

Not sure if this is the problem but you never know which this is this in javascript.

This fixed the fiddler so it is most likely your issue. So the issue incase you don't see it is you are using the incorrect "this" inside of your register.

Parameters sent using the .$broadcast has to be sent as a object, not as seperate arguments. Here is an example:

$rootScope.$broadcast("register", {
    'username': username,
    'password': password
});

http://jsfiddle.net/7LLa7zot/5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM