gpt4 book ai didi

javascript - ng-显示未更新

转载 作者:行者123 更新时间:2023-12-02 16:14:37 24 4
gpt4 key购买 nike

我试图通过广播来切换当前正在显示的 View ,但是当我更改 Controller 的模型时,ng-show 不会更改以反射(reflect)新状态。

我使用 $rootScope.$broadcast("registerFormShow", username, password) 告诉 RegisterForm Controller 我希望它可见。它有一个我在 ng-show 中的变量 register.active ,但它似乎没有应用更改。我尝试从 $on 回调中调用 $scope.$apply() ,但 Angular 抛出异常,表示 $apply 已在进行中。有什么想法为什么会发生这种情况吗?

这是我的一些代码:

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/

最佳答案

我会尝试

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

不确定这是否是问题所在,但你永远不知道 JavaScript 中的 this 是什么。

这修复了 fiddle 手,因此这很可能是您的问题。因此,如果您没有看到它,问题是您在寄存器中使用了不正确的“this”。

关于javascript - ng-显示未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29807615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com