我有一个NavbarCtrl不在ng视图之外。我有一个登录控制器,与一个服务进行交谈,以便用户登录。一旦用户登录,我希望Navbar更新用户的电子邮件地址。但是对于我来说,一旦用户登录,我似乎无法让Navbar范围更新为加载到我的“Auth”服务的数据。
这是我的主要index.html:
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">Brim</a>
<div class="pull-right" ng-controller="NavbarCtrl">
<div ng-click="refresh()">hello</div>
{{ user.email }}
</div>
</div>
</div>
</div>
<div class="container" ng-view>
和我的服务:
.factory('Auth',function($resource) {
var authenticated = false;
var user = {};
return {
isAuthenticated: function () {
return authenticated;
},getUser: function() {
return user;
},login: function(loginUser,callback) {
user = {email:'email@email.com'}
authenticated = true;
callback(true);
//actual code for logging in taken out for brevity
}
}
})
和我的登录和导航栏控制器:
function LoginCtrl($scope,$location,Auth) {
$scope.login = function() {
Auth.login($scope.user,function(success) {
if(success) $location.path('/dashboard');
//console.log(Auth.getUser())
});
}
}
function NavbarCtrl($scope,Auth) {
//thought this should work
$scope.user = Auth.getUser();
//experimenting unsuccessfully with $watch
$scope.$watch(Auth.isAuthenticated(),function () {
$scope.user = Auth.getUser()
})
//clicking on a refresh button is the only way I can get this to work
$scope.refresh = function() {
$scope.user = Auth.getUser()
}
}
从我的研究我会以为$ scope.user = Auth.getUser();会工作,但不是,我完全失去了如何在用户登录时如何更新我的Navbar。提前感谢任何帮助。
更新:嗯,你每天都会学到新的东西…只需删除()来观察一个函数的结果:
$scope.$watch(Auth.isAuthenticated,function() { ... });
Updated fiddle
在这个小提琴中,注意当$ scope.isAuthenticated的值改变时,’watch1’和’watch3’两者都会触发第二次。
因此,这是一种通用技术,用于监视在服务上定义的原始值的更改:
>定义一个API /方法返回(的值)的基元
> $表示该方法
要监视在服务上定义的对象或数组的更改:
>定义返回(引用)对象/数组的API /方法
>在服务中,请小心只修改对象/数组,不要重新分配。例如:user = …;而不是这样做:angular.copy(newInfo,user)或者这个:user.email = …
通常你会为该方法的结果分配一个本地的$ scope属性,因此$ scope属性将是对实际对象/数组的引用
> $ watch范围属性
例:
$scope.user = Auth.getUser();
// Because user is a reference to an object,if you change the object
// in the service (i.e.,you do not reassign it),$scope.user will
// likewise change.
$scope.$watch('user',function(newValue) { ... },true);
// Above,the 3rd parameter to $watch is set to 'true' to compare
// equality rather than reference. If you are using Angular 1.2+
// use $watchCollection() instead:
$scope.$watchCollection('user',function(newValue) { ... });
原始答案:
要观察一个函数的结果,你需要传递$ watch一个包含该函数的函数:
$scope.$watch( function() { return Auth.isAuthenticated() },function() { ... });
Fiddle.在小提琴中,注意当$ scope.isAuthenticated的值发生变化时,只有“watch3”会再次触发。 (它们都初始触发,作为$ watch初始化的一部分。)