我有一个工作指令,它在ng-model和checkbox对象数组之间创建双向绑定。用法:
<div hardware-ids-picker ng-model="dataflow.idTypes"></div>
以下是指令中的双向绑定代码,其中hardwareIds
是复选框:
// model --> view
ngModel.$viewValue.forEach(function (id) {
hardwareIds.forEach(function (hardwareId) {
if (id === hardwareId.value) hardwareId.__checked = true;
});
});
// view --> model
scope.$watch("hardwareIds", function (hardwareIds) {
var hardwareIds = HardwareIdsService.bindIds(hardwareIds);
ngModel.$setViewValue(hardwareIds);
}, true);
我已经阅读here,正确的方法是使用Angular的$formatters
和$parsers
服务,所以我尝试将格式化功能推送到ngModel.$formatters
数组:
function formatter(modelValue) {
modelValue.forEach(function (id) {
scope.hardwareIds.forEach(function (hardwareId) {
if (id === hardwareId.value) hardwareId.__checked = true;
});
});
return scope.hardwareIds;
}
ngModel.$formatters.push(formatter);
ngModel.$render();
我返回一个应该设置为$viewValue
的对象数组,然后使用ngModel.$render()
函数在DOM中显示它,但它不能正常工作
我做错了什么?或者我的原始工作解决方案是否可以接受?