问题描述
限时送ChatGPT账号..我的问题是创建一个角度指令.
my problem is with creating an angular directive.
我想用一个单一的 ng-model 创建一组复选框.它就像一个位域或标志,即复选框的值从 0、1、2、3 到 n,但对于 ng-model,我只想添加所有选中复选框的 2^value.要添加的值是 1, 2, 4, 8, 16, ...
I want to create a group of checkboxes with just one single ng-model. It's like a bitfield or flags, i.e. the checkboxes have values from 0, 1, 2, 3 up to n but for ng-model I just want to add 2^value of all checked checkboxes. The values to add are then 1, 2, 4, 8, 16, ...
我想知道是否有更好、更正确或更简单的解决方案来解决我的问题.
I wonder if there is a better, more correct or just simpler solution to my problem.
http://plnkr.co/edit/9h7EkEpDohXTniIDHdc5
在示例中,您可以更改文本框中的值,检查将被更新,但不能以其他方式更新.有点疯狂,代码可以在我的开发机器上运行,但不能在 Plnkr 中运行!
In the example you can change the value in the textbox and the checks will be updated, but not the other way. It's a bit crazy, the code is working on my dev machine, but not in Plnkr!
app.directive('ngCheckboxFlags', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrls) {
var flagSum;
var checkboxes = [];
// trigger changes of the ngModel
scope.$watch(attrs.ngModel, function (value) {
flagSum = value;
for (var i = 0, ii = checkboxes.length; i < ii; ++i) {
var checkbox = checkboxes[i];
checkbox.checked = flagSum & (1<<checkbox.value);
}
});
for (var i = 0, inputs = element.find('input[type=checkbox]'), ii = inputs.length; i < ii; ++i)
{
var checkbox = inputs[i];
checkboxes.push(checkbox);
// trigger changes of HTML elements
$(checkbox).bind('change', function () {
flagSum = ctrls.$viewValue ^ (1<<this.value);
console.log(flagSum);
//ERROR: Change not happening, textbox shows old value
scope.$apply(function () {
ctrls.$setViewValue(flagSum);
});
});
}
}
};
});
提前谢谢纽特
推荐答案
不要将 ng-model
直接绑定到原始类型,而是使用对象:
Don't bind the ng-model
directly to primitive types, use an object instead:
$scope.sum = {
ofCheckValues: 3
};
在 HTML 上:
ng-model="sum.ofCheckValues"
每当你有 ng-model 时,就一定有一个点在那里.如果你没有点,那你就做错了."
plunker:http://plnkr.co/edit/NRAk3kyP1rdDmYrsz6ZL?p=预览
这篇关于带有子元素的角度双向绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论