我有一个应用程序,应用程序内部有一个注册和登录表单。
通过注册表单,当用户创建帐户时,他们会自动登录。
通过登录表单,用户也可以登录(显然)。
我有两个控制器:一个用于注册表单,一个用于登录表单。我希望他们能够共享一个服务“logIn”,因为两种形式的用户最终都会登录。
到目前为止它正在发挥作用。我唯一的问题是登录表单根据数据库异步检查用户的登录凭据,如果处理此请求的 PHP 脚本返回说不存在匹配,则 Angular 会更新错误消息的模型,如图所示给用户。当“logIn”服务不用作服务而只是复制到两个控制器中时,这种方法工作得非常好。这是它在“SignupCtrl”中的样子:
.controller('SignupCtrl',['$scope','$http',function($scope,$http) {
$scope.error = false;
$scope.logIn = function() {
var data = // user's login credentials
$http({
// send credentials to server, ask if there's a match
})
.success(function(data) {
if(data.match === false) {
$scope.error = true;
} else {
// start session, redirect to new page, etc.
}
})
}
}]);
然后,在模板内部:
<div ng-show="error">Oops! That email/password doesn't exist.</div>
这很好用;但正如我所说,当“登录”功能用作服务时则不然。这是因为我不知道如何更新$scope.error
服务内部。
我尝试过使用$rootScope
(这不起作用):
.service('logIn',[/* injections */, '$rootScope', function(/* injections */, $rootScope) {
return function(email, password) {
// all the same code as before
if(data.match === false) {
$rootScope.error = true; // this does nothing
}
}
}]);
// in the controller (the service is injected in as 'logIn')
$scope.logIn = logIn;
然后,在模板中:
<button ng-click="logIn(user.email, user.password)">Login</button>
用户可以正常登录该服务。问题只是更新$scope.error
随服务而变化。
也许如果我能以某种方式做到这一点,它会起作用:
<button ng-click="logIn(user.email, user.password, $scope)">Login</button>
然后在服务中:
return function(email, password, scope) {
// etc.
if(data.match === false) {
scope.error = true;
}
}
有什么想法吗?谢谢。
小编辑
只是为了澄清,根据我的理解services
,它们似乎取代了人们通常声明全局函数的方式,或者只是模块内的整体函数,以避免重复。例子:
(function() {
function globalFunction() {
//etc.
}
$('.thing').click(globalFunction);
$('.otherThing').click(globalFunction);
}());
可能有比这更好的例子,但我认为这个想法很清楚。
这个概念与 Angular 内部如何使用服务类似吗?如果没有,是否有更好的方法可以让我在不使用服务的情况下完成我想做的事情?