触发自定义验证指令后,AngularJS ng-model值将丢失

Dav*_* Z. 6 angularjs angularjs-directive angularjs-scope angular-ngmodel

我创建了一个自定义验证指令并在表单中使用它.它可以毫无问题地触发,但在触发验证后,我发现模型值刚刚丢失.说我有

ng-model="project.key" 
Run Code Online (Sandbox Code Playgroud)

并且在验证之后,project.key范围内不再存在.我想某种程度上我理解AngularJS错了并做错了什么.

代码说话.

这是我的html页面:

 <div class="container">
    ...
    <div class="form-group"
            ng-class="{'has-error': form.key.$invalid && form.key.$dirty}">
            <label for="key" class="col-sm-2 control-label">Key</label>
            <div class="col-sm-10">
                <input type="text" class="form-control text-uppercase" name="key"
                    ng-model="project.key" ng-model-options="{ debounce: 700 }"
                    placeholder="unique key used in url"
                    my-uniquekey="vcs.stream.isProjectKeyValid" required />
                <div ng-messages="form.key.$error" ng-if="form.key.$dirty"
                    class="help-block">
                    <div ng-message="required">Project key is required.</div>
                    <div ng-message="loading">Checking if key is valid...</div>
                    <div ng-message="keyTaken">Project key already in use, please
                        use another one.</div>
                </div>
            </div>
        </div>
    <div class="col-sm-offset-5 col-sm-10">
        <br> <a href="#/" class="btn">Cancel</a>
        <button ng-click="save()" ng-disabled="form.$invalid"
            class="btn btn-primary">Save</button>
        <button ng-click="destroy()" ng-show="project.$key"
            class="btn btn-danger">Delete</button>
    </div>
</form>
Run Code Online (Sandbox Code Playgroud)

这是我的指示:

    .directive('myUniquekey', function($http) {
        return {
            restrict : 'A',
            require : 'ngModel',
            link : function(scope, elem, attrs, ctrl) {
                var requestTypeValue = attrs.myUniquekey;

                ctrl.$parsers.unshift(function(viewValue) {
                    // if (viewValue == undefined || viewValue == null
                    // || viewValue == "") {
                    // ctrl.$setValidity('required', false);
                    // } else {
                    // ctrl.$setValidity('required', true);
                    // }

                    setAsLoading(true);
                    setAsValid(false);

                    $http.get('/prism-cmti/2.1', {
                        params : {
                            requestType : requestTypeValue,
                            projectKey : viewValue.toUpperCase()
                        }
                    }).success(function(data) {
                        var isValid = data.isValid;
                        if (isValid) {
                            setAsLoading(false);
                            setAsValid(true);

                        } else {
                            setAsLoading(false);
                            setAsValid(false);
                        }
                    });

                    return viewValue;
                });

                function setAsLoading(bool) {
                    ctrl.$setValidity('loading', !bool);
                }

                function setAsValid(bool) {
                    ctrl.$setValidity('keyTaken', bool);
                }

            }
        };
    });
Run Code Online (Sandbox Code Playgroud)

这是表单页面的控制器:

angular.module('psm3App').controller(
        'ProjectCreateCtrl',
        [ '$scope', '$http', '$routeParams', '$location',
                function($scope, $http, $routeParams, $location) {
                    $scope.save = function() {
                            $http.post('/prism-cmti/2.1', {requestType:'vcs.stream.addProject', project:$scope.project})
                            .success(function(data) {
                                $location.path("/");
                            });
                        };
                }]);
Run Code Online (Sandbox Code Playgroud)

在此错误之前,我需要以某种方式在自定义验证指令中处理所需的验证,如果我不这样做,则必需的验证会出错.现在我想到了,也许这两个问题的根本原因是相同的:模型值在我的指令链接功能被触发后消失了.

我正在使用Angular1.3 Beta 18 BTW.

任何帮助表示赞赏.提前致谢.

更新: 其次@ ClarkPan的答案,我要更新了我的代码return viewValuectrl.$parsers.unshift()马上,这使得required验证现在工作很好,所以我不需要任何以下多行.

        // if (viewValue == undefined || viewValue == null
                    // || viewValue == "") {
                    // ctrl.$setValidity('required', false);
                    // } else {
                    // ctrl.$setValidity('required', true);
                    // }
Run Code Online (Sandbox Code Playgroud)

{{project.key}}仍然没有得到更新.然后我试着在这里注释掉这两行:

                    setAsLoading(true);
                    setAsValid(false);
Run Code Online (Sandbox Code Playgroud)

模型值{{project.key}}已更新.我知道如果任何验证失败,模型值将被清除,但我想

                      function(data) {
                            var isValid = data.isValid;
                            if (isValid) {
                                setAsLoading(false);
                                setAsValid(true);
                            } else {
                                setAsLoading(false);
                                setAsValid(false);
                            }
                        }
Run Code Online (Sandbox Code Playgroud)

in $http.get(...).success()应该在$ digest循环中执行,这意味着应该更新模型值.

怎么了?

小智 5

发生这种情况是因为,如果在模型中设置了任何无效标志,则angular不会对范围和$ modelValue进行任何更改。当您开始验证过程时,您会将'keyTaken'有效性标志设置为false。就是说不要将角度值应用到模型。当ajax响应到达并且您将'keyTaken'有效性标志设置为true时,$ modelValue已经设置为undefined并且属性'key'消失了。尝试在ajax请求期间将所有有效性标志设置为true。在ajax调用之前,必须避免调用setAsLoading(true)和setAsValid(false),并将所有有效性标志设置为true。仅在ajax响应之后设置有效性标志。

  • 您好,超过两年!我遇到了类似的问题,在查看https://docs.angularjs.org/api/ng/directive/ngModelOptions上的文档后,有一个allowInvalid选项,当设置为true时,它允许无效值更新模型!祝大家开心! (6认同)