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:初始复选框值不在模型中
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
