Angularjs directive to make form dirty without ng-

2019-08-09 22:50发布

问题:

I am using Angular 1.5.1. I have a checkbox on my form. I do not care about the truth/false indicator of the checkbox being checked/unchecked and so I do not want ng-model on it. What I care for is:

  • when checkbox is unchecked, I delete a specific array from my model
  • when checkbox is checked, I add an empty array back to my model

So I have created a directive that provides me with this functionality, very simple:

.directive('cbOnChecked', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attr) {
            element.on('click', function(event) {
                if(element[0].checked)
                    scope.$apply(attr.cbOnChecked);
            });
        }
    };
})

.directive('cbOnUnchecked', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attr) {
            element.on('click', function(event) {
                if(!element[0].checked)
                    scope.$apply(attr.cbOnUnchecked);
            });
        }
    };
})

Now I can do something like:

<input type="checkbox" cb-on-checked="counter = counter + 1" cb-on-unchecked="counter = counter - 1"/>

Or

<input type="checkbox" cb-on-checked="deleteUserList()" cb-on-unchecked="users = []"/> No users<br/>

The problem with this is - the form within which the checkbox is won't get marked as $dirty if there is no ng-model on the checkbox. Is there any way around this?
Here is an example js-fiddle. Thanks.

回答1:

If you really want to go with your own directives you can just require parent form controller and mark it $dirty manually:

.directive('cbOnChecked', function() {
    return {
        require: '^form',
        restrict: 'A',
        link: function(scope, element, attr, ngFormController) {
            element.on('click', function(event) {
              ngFormController.$setDirty();
              if(element[0].checked)
                scope.$apply(attr.cbOnChecked);
            });
        }
    };
})