我有一个非常愚蠢的问题,我希望有人可以帮助我更好地理解AngularJS,同时我会浏览更多文档......请注意我已经和AngularJS一起工作了一周,因为我有无论如何都从同事那里继承了一个项目......
与我的项目相关联的单元测试失败,并显示以下错误消息"scope.signupForm is undefined in /Users/.../.../.../app/login/login.js"
在WebStorm中,我的代码正在突出显示(带下划线的灰色),并显示以下消息“未解析的变量signinForm”& “Unresolved Variable signupForm”,提出此代码的代码低于......
这是控制器的一部分...
function LoginController($scope, userService) {
$scope.loggedInUser = null;
$scope.signIn = function (user) {
console.log("SignIn");
$scope.loggedInUser = { userName: user.userName };
$scope.user = undefined;
$scope.signinForm.$setPristine(); // Error here is "Unresolved Variable signinForm"
};
$scope.register = function (user) {
console.log("Register");
$scope.loggedInUser = user;
$scope.user = undefined;
console.log(user);
userService.addUser(user);
$scope.signupForm.$setPristine();// Error here is "Unresolved Variable signupForm"
};
$scope.signOut = function () {
console.log("SignOut");
$scope.loggedInUser = undefined;
$scope.signInVisible = false;
};
... // more code here
现在这是我在视图中包含的HTML代码(想要更好的词)
<div id="login-signin" class="loginLeftBox">
<form name="signinForm" novalidate ng-submit="signIn(loginUser)" autocomplete="off">
<div> ... Form Stuff...</div>
</form>
<div ng-show="signinForm.userName.$dirty && signupForm.userName.$invalid">
... Validation Stuff...
</div>
<div ng-show="signinForm.password.$dirty && signupForm.password.$invalid">
... Validation Stuff...
</div>
</div>
<div id="login-register" class="loginRightBox">
<form name="signupForm" novalidate ng-submit="register(user)" autocomplete="off">
... Form Stuff...
</form>
</div>
任何解释都将不胜感激......
答案 0 :(得分:0)
您必须将控制器放在与表单相同的级别:
<form name="signinForm" ng-controller="SinginFormCtrl" ...>
然后SinginFormCtrl
将在范围内具有signinForm
,例如:
function SinginFormCtrl($scope, userService) {
$scope.signIn = function (user) {
...
$scope.signinForm.$setPristine(); // WILL WORK NOW
};
...
}
这可能意味着您需要稍微重新构建代码。
答案 1 :(得分:0)
我发现,在将$ scope写入控制台$scope.signinForm
&amp; $scope.signupForm
存在和定义的地方!因此,我向控制器添加了以下条件,现在所有单元测试似乎都有效?
reset = function(){
if($scope.signinForm){
$scope.signinForm.$setPristine();
}
if($scope.signinForm){
$scope.signupForm.$setPristine();
}
};
不确定这是解决方案还是黑客?