我有一个表单,我正试图通过自定义身份验证服务通过ng-submit事件提交。
login.html(部分模板(
<div class='container'>
<form class='form-signin' role='form' ng-submit='login()'>
<h2 class='form-signin-heading'>dotAdmin login</h2>
<input type='email' class='form-control' placeholder='Email Address' ng-model='email' required autofocus>
<input type='password' class='form-control' placeholder='Password' ng-model='password' required>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div>
services.js
/* Services */
var dotAdminServices = angular.module('dotAdminServices', []);
// don't know if loading http and rootscope dependencies are redundant
dotAdminServices.factory('SessionService', [function () {
return {
isLogged: false,
userId: null,
name: null,
email: null,
password: null,
imageUrl: null,
coverUrl: null
};
}]);
dotAdminServices.factory('AuthService',['$http', 'SessionService', '$location',
function ($http, SessionService, $location) {
var login = function (email, pw) {
$http.post('http://54.187.31.161/api/v1/users/sign_in', {'email': email, 'password': pw}).
success(function (data) {
SessionService.isLogged = true,
SessionService.name = data.name,
SessionService.id = data.id,
SessionService.email = email,
SessionService.password = pw,
SessionService.coverUrl = data.coverUrl,
SessionService.imageUrl = data.imageUrl;
$location.url('/dashboard');
}
).
error(function(){
SessionService.isLogged = false,
SessionService.name = null,
SessionService.id = null,
SessionService.email = null,
SessionService.password = null,
SessionService.coverUrl = null,
SessionService.imageUrl = null;
}
);
};
var logout = function () {
$http.delete('http://54.187.31.161/api/v1/users/sign_out', {'email': email, 'password': pw}).
success(function () {
SessionService.isLogged = false,
SessionService.name = null,
SessionService.id = null,
SessionService.email = null,
SessionService.password = null,
SessionService.coverUrl = null,
SessionService.imageUrl = null;
});
};
}]);
和控制器js
/* Controllers */
var dotAdminControllers = angular.module('dotAdminControllers', []);
dotAdminControllers.
controller('loginCtrl', ['SessionService', 'AuthService', '$location', '$http', '$scope',
function($scope, $http, $location, SessionService, AuthService){
$scope.dummy = 'stringtest';
$scope.login = function () {
alert('function executed');
};
}
]);
有趣的是:当我运行单元测试来访问范围变量时,它们似乎都是未定义的。我还尝试在$scope中定义一个伪变量,并在login.html上使用{{dummy}}进行测试,但它没有绑定,也没有出现在页面上。此外,当我在controller.js中设置断点时,所有ServiceSession变量似乎都在本地范围内。我很困惑。是否存在多个变量作用域,注入器将这些变量作用域折叠到本地作用域中?我意识到事件处理程序不会触发,因为它在页面加载时是未定义的,但为什么会发生这种情况?
提前非常感谢您的回复,感谢您在我冗长的帖子中跋涉。
使用内联数组的依赖项注入将按声明的顺序传递依赖项。因此,在您的情况下,函数params应该如下所示:
function(SessionService, AuthService, $location, $http, $scope)
目前,您在函数中调用的$scope
实际上是SessionService
,因为它是第一个依赖项。