3

我现在尝试将我的遗留应用程序迁移到 Angular,现在遇到了以下问题。我有这个简单的形式:

<form name="loginForm" ng-controller="LoginCtrl" ng-submit="doLogin()">
  <input type="text" name="login" ng-model="login.login" />
  <span class="errors" ng-show="loginForm.login.$error.required">Required</span>
  <span class="errors" ng-show="loginForm.login.$error.bad_login">Login or pass incorrect</span>
  <input type="password" ng-model="login.pass"/>
</form>

服务器以这种 JSON 类型返回错误: { login: 'bad_login', pass: 'incorrect' } 并且在控制器中:

function LoginCtrl($scope, $http) {

    $scope.doLogin = function() {
        var model = $scope.login;
        var req = { "login": model.login, "pass": model.pass };
        $http({ method: "POST", url: "/login", data: req }).success(function (resp) {
            if(resp.status != "ok") {
                angular.forEach(resp, function (value, key) {
                    // ex: model['login'].$setValidity('bad_login', false);
                    model[key].$setValidity(value, false);
                });
            }
        });
    };
}

我尝试在循环中标记每个字段,而不是手动对每个字段进行硬编码。但这种方法不起作用。我收到此错误:TypeError: Cannot call method '$setValidity' of undefined,即使字段为空,我还有另一个错误:TypeError: Cannot read property 'login' of undefined 所以我认为我需要为表单中的每个字段获取模型实例,有什么想法吗?

4

1 回答 1

3

它返回未定义的原因是因为除非您实际上为 $scope.login.login 或 $scope.login.pass 指定了某些内容,否则它们不会被设置。如果您放置一个空格并删除它,您会看到它们被设置为空白。您要做的是在控制器的开头定义范围上的登录,如下所示:

function LoginCtrl($scope, $http) {
    $scope.login = {
        login: "",
        pass: ""
    };
    $scope.doLogin = function() {
        var req = { "login": $scope.login.login, "pass": $scope.login.pass };
        $http({ method: "POST", url: "/login", data: req }).success(function (resp) {
            if(resp.status != "ok") {
                angular.forEach(resp, function (value, key) {
                    // ex: model['login'].$setValidity('bad_login', false);
                    $scope.login[key].$setValidity(value, false);
                });
            }
        });
    };
}
于 2012-12-26T15:59:53.803 回答