ng-switch 没有按预期工作
ng-switch is not working as expected
也许 2 向绑定和 $watch
的使用对我来说仍然不是很清楚..但我期待这段代码应该有效!
我的 index.html 页面中有一个 topNavbar 指令。如果用户未登录,topNavbar 应该显示 loginButton,否则如果用户已经登录,则显示 loggedinButton已记录。
所以我在topNavbar中有一个ng-switch
,查看的isLogged属性当前用户服务。我想这类似于 $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();}
}
当前用户服务
.service('CurrentUserService', function ()
{
// initialization
_islogged = false;
this.isLogged = function()
{ return _islogged; };
}
谢谢
这里是plunker.
Angular 在模型发生变化时启动摘要循环(这就是为什么在您以某种方式与 UI 交互后您注意到它更新的原因)。
服务内部闭包变量的更改不是模型的一部分,因此当您知道此变量已更新时,您需要手动 $scope.$apply()
启动摘要循环。
也许 2 向绑定和 $watch
的使用对我来说仍然不是很清楚..但我期待这段代码应该有效!
我的 index.html 页面中有一个 topNavbar 指令。如果用户未登录,topNavbar 应该显示 loginButton,否则如果用户已经登录,则显示 loggedinButton已记录。
所以我在topNavbar中有一个ng-switch
,查看的isLogged属性当前用户服务。我想这类似于 $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();}
}
当前用户服务
.service('CurrentUserService', function ()
{
// initialization
_islogged = false;
this.isLogged = function()
{ return _islogged; };
}
谢谢
这里是plunker.
Angular 在模型发生变化时启动摘要循环(这就是为什么在您以某种方式与 UI 交互后您注意到它更新的原因)。
服务内部闭包变量的更改不是模型的一部分,因此当您知道此变量已更新时,您需要手动 $scope.$apply()
启动摘要循环。