Javascript 当用户操作完成时更新AngularJS视图
我正在写一些小练习来教自己AngularJS,我正在尝试写一些简单的用户授权任务。我有一个表单来收集/输入用户名和密码,然后使用Javascript 当用户操作完成时更新AngularJS视图,javascript,angularjs,Javascript,Angularjs,我正在写一些小练习来教自己AngularJS,我正在尝试写一些简单的用户授权任务。我有一个表单来收集/输入用户名和密码,然后使用$http和CORS将它们发送到rest服务(因为我的rest服务在不同的端口上运行),检查它们,如果存在匹配项,我将返回UUID并创建一个令牌,然后在$rootScope上将loggedIn值设置为true,类似于这样 // this is in a service I call 'authService' this.login = function (user)
$http
和CORS将它们发送到rest服务(因为我的rest服务在不同的端口上运行),检查它们,如果存在匹配项,我将返回UUID并创建一个令牌,然后在$rootScope
上将loggedIn值设置为true,类似于这样
// this is in a service I call 'authService'
this.login = function (user) {
return $http({method: 'POST', url: 'http://127.0.0.1:3000/login', data: user})
.then(function (response) {
// set up a local storage token
storageService.setLocalStorage('token', response.data[0].uuid);
// broadCast is loggedIn - we have a match
$rootScope.loggedInUser = true; // this is set to false at the .run() of the app
$rootScope.$broadcast('LoggedIn');
return 1;
}, function () {
// return http code later
return 0;
});
};
this.getLoggedIn = function () {
return $rootScope.loggedInUser;
};
现在,在一个单独的菜单视图中,我有以下条件(authService作为菜单控制器的依赖项添加):
好的,当我更改$rootScope.loggedInUser时,我菜单视图中
上的条件没有更新。我的方法有问题,有人能给我一些建议或纠正我的方法吗。谢谢如果某个道具在正确的范围内更新,您不必在角度视图中执行任何特殊操作来更新视图。我为您提供了一个Plunkr,它表明您不必做任何特殊的事情来刷新视图
你不必做手表,你什么都不用做。这就是角度的力量。另外,在rootscope中设置东西也很奇怪。我给你的建议是看看我的例子,修改/重组你的代码。还有,有这样的东西:
ng show=“!authService.getLoggedIn()”
这不是推荐的做事方式。你可以有一个控制器,其中你说:
$scope.userLoggedIn = autService.getLoggedIn();
在你看来:
ng-show="userLoggedIn"
您也可以看看这个plunkr:
ng show
绑定到范围值,如$scope.isLogon
或返回true或false的范围函数<代码>authService.getLoggedIn()未定义,或者至少未在此处显示的代码中定义。这意味着authService.getLoggedIn()
始终为false。对不起,authService.getLoggedIn()是在服务中定义的,我将其作为依赖项添加到菜单控制器中,因此当我登录console.log(authService.getLoggedIn())时;和$scope.$watch('loggedInUser'函数(){})在控制器中被激发,但视图没有更新?视图没有访问authService的权限,您可以在菜单控制器中执行代理authService.getLoggedIn()
。比如$scope。getAuth=function(){return authService.getLoggedIn()}
。此外,我并不认为有必要在您的用例中包含rootScope。
$scope.userLoggedIn = autService.getLoggedIn();
ng-show="userLoggedIn"