如何在AngularJS中使用指令$ setDirty()表单

时间:2016-10-18 14:05:06

标签: angularjs

当输入框改变时,我想将表单设置为脏。我想使用指令。这就是我已经做过的事情。

HTML:

<form name="myForm">
    <type="text" ng-model="myModel" set-form-dirty>
</form>

指令:

app.directive('setFormDirty', function () {
 return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
           scope.$watch(function () {
              return ngModel.$modelValue;
           }, function(newValue) {
               console.log(newValue);
            // Here I should set form to dirty. But I don't know how?
           });
        }
     };
});

@EDIT

我需要这个,因为myModel正在通过不同的功能而改变。该功能不会将格式设置为$dirty

2 个答案:

答案 0 :(得分:0)

您可以在ngModelController上观看modelvalue。

.directive('setFormDirty', function(){
  return {
    require: 'ngModel',
    link: function (scope, element, attrs, ngModel) {

        scope.$watch(function(){
          return ngModel.$modelValue;
        },function(newValue, oldValue){
          //Check stuff here and use below code to set it to dirty
          ngModel.setDirty();
        });
    }
  };

答案 1 :(得分:0)

以这种方式解决:

angular.module("qs.forms").directive("setFormDirty", function () {
    return {
        require: ["ngModel", "^form"],
        link: function (scope, element, attrs, ctrls) {
            scope.$watch(function () {
                return ctrls[0].$modelValue;
            }, function (newValue) {
                if (newValue) {
                    ctrls[1].$dirty = true;
                }
            });
        }
    };
});

表格可以通过require: ["ngModel", "^form"],

传递