Angular.js programmatically setting a form field to dirty

后端 未结 11 1981
孤独总比滥情好
孤独总比滥情好 2020-12-02 10:57

I am programmatically updating some of the fields on my form with a value and I would like to set the field state to $dirty. Doing something like:

相关标签:
11条回答
  • 2020-12-02 11:33

    I'm not sure exactly why you're trying to mark the fields dirty, but I found myself in a similar situation because I wanted validation errors to show up when somebody attempted to submit an invalid form. I ended up using jQuery to remove the .ng-pristine class tags and add .ng-dirty class tags to the appropriate fields. For example:

    $scope.submit = function() {
        // `formName` is the value of the `name` attribute on your `form` tag
        if (this.formName.$invalid)
        {
            $('.ng-invalid:not("form")').each(function() {
                $(this).removeClass('ng-pristine').addClass('ng-dirty');
            });
            // the form element itself is index zero, so the first input is typically at index 1
            $('.ng-invalid')[1].focus();
        }
    }
    
    0 讨论(0)
  • 2020-12-02 11:34

    This is what worked for me

    $scope.form_name.field_name.$setDirty()
    
    0 讨论(0)
  • 2020-12-02 11:40

    A helper function to do the job:

    function setDirtyForm(form) {
        angular.forEach(form.$error, function(type) {
            angular.forEach(type, function(field) {
                field.$setDirty();
            });
        });
        return form;
    }
    
    0 讨论(0)
  • 2020-12-02 11:42

    In your case, $scope.myForm.username.$setViewValue($scope.myForm.username.$viewValue); does the trick - it makes both the form and the field dirty, and appends appropriate CSS classes.

    Just to be honest, I found this solution in new post in the topic from the link from your question. It worked perfectly for me, so I am putting this here as a standalone answer to make it easier to be found.

    EDIT:

    Above solution works best for Angular version up to 1.3.3. Starting with 1.3.4 you should use newly exposed API method $setDirty() from ngModel.NgModelController.

    0 讨论(0)
  • 2020-12-02 11:44

    You can use $setDirty(); method. See documentation https://docs.angularjs.org/api/ng/type/form.FormController

    Example:

    $scope.myForm.$setDirty();
    
    0 讨论(0)
提交回复
热议问题