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

查看:135
本文介绍了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"/>

现在我想有它的初始值(原因是其被选中)绑定到模型,而无需点击复选框。有没有除了在控制器中手动设置模型值或使用方法 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.

推荐答案

也许这是这样的一个指令:

Maybe a directive that works like this:

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

以下code应该这样做:

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天全站免登陆