AngularJS:初始复选框值不在模型中 [英] AngularJS: Initial checkbox value not in model

查看:31
本文介绍了AngularJS:初始复选框值不在模型中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有这样复选框的表单:

I have got a form with a checkbox like this:

<input type="checkbox" name="publish" id="publish" ng-model="data.publish" ng-true-value="Yes" ng-false-value="No"/>

现在我想将其初始值 'No'(因为它未选中)绑定到模型,而无需单击复选框.除了在控制器中手动设置模型值或使用 ngInit 之外,还有其他方法吗?

Now I would like to have its initial value 'No' (becuase it is unchecked) bound to the model without having to click on the checkbox. Is there a way besides setting the model value manually in the controller or using ngInit?

我的脚本应该适用于不同的形式,因此手动设置模型变量是不可行的.而且 ngInit 方法看起来相当不优雅.

My script should work with different forms so manually setting model variables is no option. And the ngInit method seems rather inelegant.

推荐答案

可能是这样的指令:

<input type="checkbox" ng-model="..." init-cb ... />

下面的代码应该做到这一点:

The following code should do it:

m.directive("initCb", function() {
    return {
        require: ["ngModel"],
        scope: false,
        link: function(scope, element, attrs, controllers) {
            var ngModel = controllers[0],
            if( element[0].checked ) {
                ngModel.$setViewValue(attrs.ngTrueValue || true);
            }
            else {
                ngModel.$setViewValue(attrs.ngFalseValue || false);
            }
        }
    };
});

这篇关于AngularJS:初始复选框值不在模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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