角双向绑定与子元素 [英] Angular two-way-binding with sub elements
问题描述
我的问题是建立一个角度指令。
my problem is with creating an angular directive.
我要创建一组复选框只有一个单一的NG-模式。这就像一个位域或标志,即复选框具有值从0,1,2,3直到n但是对于NG-模式,我只想补充的是2 ^值选中的复选框。添加的值是接着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
在这个例子中你可以改变文本框中的值,检查将被更新,而不是其他的方式。这是一个有点疯狂,在code正在我的dev的机器上,而不是在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);
});
});
}
}
};
});
日Thnx提前
克努特
thnx in advance knut
推荐答案
不绑定的 NG-模型
直接向原始类型,使用对象来代替:
Don't bind the ng-model
directly to primitive types, use an object instead:
$scope.sum = {
ofCheckValues: 3
};
和在HTML:
ng-model="sum.ofCheckValues"
的每当你有NG-模型有一定有一个点在那里的某个地方。如果你没有一个点,你就错了。的
plunker :<一href=\"http://plnkr.co/edit/NRAk3kyP1rdDmYrsz6ZL?p=$p$pview\">http://plnkr.co/edit/NRAk3kyP1rdDmYrsz6ZL?p=$p$pview
这篇关于角双向绑定与子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!