AngularJS指令使表单不带ng-model变脏 [英] Angularjs directive to make form dirty without ng-model

查看:97
本文介绍了AngularJS指令使表单不带ng-model变脏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 1.5.1.我的表格上有一个复选框.我不在乎复选框被选中/未选中的真/假指示符,因此我不希望在其上使用ng-model.我关心的是:

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:

  • 取消选中复选框时,我将从模型中删除特定数组
  • 选中此复选框后,我会向模型添加一个空数组

所以我创建了一条指令,为我提供了此功能,非常简单:

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"/>

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

此问题是-如果复选框上没有ng-model,则该复选框所在的表单将不会被标记为$dirty.有什么办法解决吗?
此处是一个js小提琴示例.谢谢.

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.

推荐答案

如果您真的想使用自己的指令,则只需要求父窗体控制器并将其手动标记为$dirty:

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);
            });
        }
    };
})

这篇关于AngularJS指令使表单不带ng-model变脏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆