也许使用双向绑定和$watch
仍然不是很清楚,但我期待这段代码应该工作!ng-switch没有按预期工作
我有一个topNavbar指令在我的index.html页面。如果用户未登录,topNavbar应该显示loginButton,否则如果他已经记录,则显示登录按钮。
所以我有一个ng-switch
在topNavbar,看着isLogged的CurrentUserService的属性。我想这是像$watch(CurrentUserService.isLogged)
。
但是,当我将CurrentUserService.isLogged
更改为true
时,ng-switch
未立即更新。它会在我的任何操作后得到更新,例如单击按钮或更改视图。 为什么它没有按照我的预期工作?
这是我的代码:
的index.html
<html lang="it" xmlns:ng="http://angularjs.org" ng-app="epoiApp">
...
<body style="overflow-y: auto;">
...
<top-navbar></top-navbar>
...
</body>
</html>
指令模板topNavbar
<div ng-switch on="navbarCtrl.isLogged()">
<div ng-switch-when="false">
<login-button></login-button>
</div>
<div ng-switch-when="true">
<loggedin-button></loggedin-button>
</div>
</div>
控制器navbarCtrl
controller:function(CurrentUserService)
{
this.isLogged = function()
{return CurrentUserService.isLogged();}
}
CurrentUserService
.service('CurrentUserService', function()
{
// initialization
_islogged = false;
this.isLogged = function()
{ return _islogged; };
}
谢谢
这里只是一个疯狂的猜测:你有没有在你的指令中忘记$ scope.apply()? – Carsten
我不使用$ scope。$ apply()...我认为它是自动的。为什么我应该手动使用$ scope。$ apply()这里,而其他地方不需要? (我的意思是,在所有其他ng-repeat,ng-model,{{ctrl.value}}等等。) – DeLac