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

相关文章