AngularJS: Initial checkbox value not in model(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:初始复选框值不在模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:AngularJS:初始复选框值不在模型中
基础教程推荐
- 在 contenteditable 中精确拖放 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
