1

我有一个非常愚蠢的问题,我希望有人可以在这里帮助我更好地理解 AngularJS,同时我浏览更多文档......请注意,我已经使用 AngularJS 一个星期了,因为我已经继承了一个项目反正是从同事那里...

与我的项目关联的单元测试失败并显示以下错误消息"scope.signupForm is undefined in /Users/.../.../.../app/login/login.js"

在 WebStorm 中,我的代码被突出显示(带下划线的灰色),并带有以下消息“ Unresolved Variable 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>

任何解释将不胜感激...

4

2 回答 2

0

You have to place your controller in the same level as the form:

<form name="signinForm" ng-controller="SinginFormCtrl" ...>

Then the SinginFormCtrl will have the signinForm in scope, e.g.:

function SinginFormCtrl($scope, userService) {
    $scope.signIn = function (user) {
        ...
        $scope.signinForm.$setPristine(); // WILL WORK NOW
    };
    ...
}

This probably means that you will have to restructure your code a bit.

于 2013-09-27T09:05:29.587 回答
0

我发现,在将 $scope 写入控制台之后,$scope.signinForm& $scope.signupFormwhere 都存在并定义了!因此,我在控制器中添加了以下条件,现在所有单元测试似乎都可以工作?

reset = function(){
    if($scope.signinForm){
        $scope.signinForm.$setPristine();
    }

    if($scope.signinForm){
        $scope.signupForm.$setPristine();
    }
};

不确定这是一个解决方案还是一个黑客?

于 2013-09-27T12:01:24.597 回答