2015-04-22 47 views
0

我试图让广播切换当前显示的视图,但是当我更改控制器的模型时,ng显示doensn不会更改以反映新状态。ng显示不更新

我使用$rootScope.$broadcast("registerFormShow", username, password)告诉RegisterForm控制器我希望它可见。它在ng显示中有一个变量register.active,但似乎并不适用这个变化。我试过在$on回调内呼叫$scope.$apply(),但是角度引发了一个异常,说$apply is already in progress。任何想法为什么发生这种情况?

下面是我的一些代码:

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> 

下面是一个演示链接演示这个问题:http://jsfiddle.net/7LLa7zot/1/

回答

1

我会尝试

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

不知道这是否是问题,但你永远不会知道这是什么在JavaScript中。

这固定了提琴手,所以它很可能是你的问题。所以这个问题一旦发生,你就不会看到你在注册表中使用了不正确的“this”。

+1

烨,该固定它。我忘记了,在回调函数中,这指向了一个不同的对象。谢谢! – CoderOfHonor

1

使用。$ broadcast发送的参数必须作为对象发送,而不是作为单独的参数发送。下面是一个例子:

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

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

+0

这不能解决问题,但你是对的。因为这个,我以后会遇到更多的问题。 – CoderOfHonor