2015-06-18 37 views
1

也许使用双向绑定和$watch仍然不是很清楚,但我期待这段代码应该工作!ng-switch没有按预期工作

我有一个topNavbar指令在我的index.html页面。如果用户未登录,topNavbar应该显示loginButton,否则如果他已经记录,则显示登录按钮

所以我有一个ng-switchtopNavbar,看着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; }; 

    } 

谢谢

+2

这里只是一个疯狂的猜测:你有没有在你的指令中忘记$ scope.apply()? – Carsten

+0

我不使用$ scope。$ apply()...我认为它是自动的。为什么我应该手动使用$ scope。$ apply()这里,而其他地方不需要? (我的意思是,在所有其他ng-repeat,ng-model,{{ctrl.value}}等等。) – DeLac

回答

2

这里是一个plunker

当模型发生变化时,Angular会启动摘要循环(这就是为什么在以某种方式与UI进行交互之后,您发现它会更新)。

服务内部的关闭变量的更改不是模型的一部分,因此您需要手动$scope.$apply()在知道此变量已更新时开始摘要循环。

+0

完美!谢谢澄清 – DeLac