1

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.

4

1 回答 1

3

如果你真的想使用你自己的指令,你可以只需要父表单控制器并$dirty手动标记它:

.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);
            });
        }
    };
})
于 2016-03-10T11:41:36.637 回答